您使用的是functional
分量不具有state
或refs
。您有兩個選項,可以將值設置爲從父項傳遞的道具或將其設爲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>
)
}
@lightspeed,該解決方案適用於功能性成分? ??????????????? –
將其轉換爲有狀態組件後,它可以正常工作,謝謝。 – lightspeed