2016-12-30 51 views
0

如何迭代DOM元素输入框。我想遍历每个<input/>。我得到错误this.refs.inputBoxes.map is not a function如何迭代DOM?

componentDidMount: function(){ 
    this.refs.inputBoxes.map(function(e, i){ 
    console.log(e) 
}) 



render: function() { 
    return (
    <div> 
     <input className= "iB" type="checkbox" ref="inputBoxes"/> 
     <input className= "iB" type="checkbox" ref="inputBoxes"/> 
     <input className= "iB" type="checkbox" ref="inputBoxes"/> 
    </div> 
) 
} 
+0

我仍然得到错误说这是不改变这种后一个功能:'ReactDOM.findDOMNode(此.refs.inputBoxes).MAP(功能(E,I){ 的console.log(E) })' – Deke

+1

信息请阅读'ReactDOM.findDOMNode'期待。你必须传入组件本身(在你的情况下是''this''''''''''''''''),因为它给了你根节点的节点,所以你得到了它的子节点。 –

回答

0

确实没有理由不只是使用document.querySelectorAll

componentDidMount: function() { 
    var inputs = document.querySelectorAll('input.iB'); 
    for (var i = 0; i < inputs.length; i++) { 
    console.log(inputs[i]); 
    } 
} 


render: function() { 
    return (
    <div> 
     <input className= "iB" type="checkbox" ref="inputBoxes"/> 
     <input className= "iB" type="checkbox" ref="inputBoxes"/> 
     <input className= "iB" type="checkbox" ref="inputBoxes"/> 
    </div> 
) 
} 
+1

呃!请不要像那样看着我...... – Deke

+1

呃!有很多原因不使用'querySelectorAll',如果页面上有其他输入框会怎么样?如果页面上有两个这样的组件会怎么样?每个查询将始终返回页面上的所有输入@Deke请不要接受这是正确的答案。 http://stackoverflow.com/a/41389208/227299有更好的方法来找到您的DOM节点 –

+0

更新以使用该类以及。 – Jack

3

我认为你只是覆盖先前设定的this.refs.inputBoxes场。如果您为多个组件设置相同的参考,我不认为它会自动变成一个数组。然而你可以给你的容器提供参考:

<div ref={e => this._inputBoxContainer = e}> 
    <input className= "iB" type="checkbox"/> 
    <input className= "iB" type="checkbox"/> 
    <input className= "iB" type="checkbox"/> 
</div> 

而在你的装载方法只需访问孩子!如果要在其上执行数组操作,你必须把它转换成数组,因为它是一个HtmlCollection

componentDidMount() { 
    Array.from(this._inputBoxContainer.children).map(e => { 
    console.log(e) 
    }) 
}