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) 
    }) 
}