2017-06-10 37 views
0

我正在創建一個跟蹤商店庫存的程序。我有項目名稱(字符串),我通過映射來生成呈現爲每個項目標題與對應的輸入字段沿組件的一個陣列:通過參考在父級訪問無狀態子組件中的輸入值

function Inventory(props){ 
    let items = ['milk', 'bread', 'butter'], 
     itemInput = items.map((value,index) => { 
     return(
     <div key={index}> 
      <h3>{value}</h3> 
      <input type={'text'} /> 
     </div> 
    ) 
    }) 

    return(
     <div> 
     {itemInput} 
     </div> 
    ) 
}; 

Screenshot of output

如何訪問兩個輸入值以及相應的標題?例如,如果我在輸入milk的輸入內鍵入5,我希望能夠訪問5milk

我已經嘗試使用refs(最終只引用最後一個數組項),eventthis無濟於事。任何建議將不勝感激。

回答

0

有可能使用這個onChange處理:

<input type="text" onChange={e => this.setState({ [value]: e.target.value })} /> 

現在的狀態會是這個樣子:

{ 
    milk: 5, 
    bread: 2, 
    butter: 10 
} 
+0

@lightspeed,該解決方案適用於功能性成分? ??????????????? –

+0

將其轉換爲有狀態組件後,它可以正常工作,謝謝。 – lightspeed

0

您使用的是functional分量不具有staterefs。您有兩個選項,可以將值設置爲從父項傳遞的道具或將其設爲stateful組件。

Stateless組件必須是專門用於渲染的啞元組件,並且所有邏輯必須駐留在stateful parent component中。

按照docs

因爲 他們沒有instances.You應該組件轉換爲類 如果你需要一個裁判不得使用對功能組件ref屬性它,就像當你需要生命週期 方法或狀態

在第一種情況下

你做
function Inventory(props){ 
     let items = ['milk', 'bread', 'butter'], 
     itemInput = items.map((val,index) => { 
     return(
     <div key={index}> 
      <h3>{val}</h3> 
      <input type={'text'} value={props.childInput[val] || '' } onChange={(e) => props.handleChange(e, val)}/> 
     </div> 
    ) 
    }) 

    return(
     <div> 
     {itemInput} 
     </div> 
    ) 
}; 

然後家長就會有像

<Inventory handleChange={this.handleChange} childInput={this.state.childInputVal}/> 


handleChange = (e, key) => { 
     var childInputVal = {...this.state.childInputVal} 
     childInputVal[key] = e.target.value 
     this.setState({childInputVal}) 
} 

state = { 
     childInputVal: {} 

} 

另一種選擇的邏輯是使該組件本身有狀態組件

class Inventory extends React.Component { 
    state= { 
     inputValues: {} 
    } 
    handleChange = (e, val) => { 
     handleChange = (e, key) => { 
     var childInputVal = {...this.state.inputValues} 
     inputValues[key] = e.target.value 
     this.setState({inputValues}) 

    } 
    render() { 
     let items = ['milk', 'bread', 'butter'], 
     itemInput = items.map((val,index) => { 
     return(
     <div key={index}> 
      <h3>{val}</h3> 
      <input type={'text'} value={this.state.inputValues[val] || '' } onChange={(e) => this.handleChange(e, val)}/> 
     </div> 
    ) 

    } 
    return(
     <div> 
     {itemInput} 
     </div> 
    ) 
} 
相關問題