您正在使用一个functional
没有的组件state
or refs
。您有两个选择,要么将值设置为从父级传递下来的 props,要么将其设为stateful
成分。
Stateless
组件必须是专门用于渲染的哑组件,并且所有逻辑必须驻留在stateful parent component
.
根据docs https://facebook.github.io/react/docs/refs-and-the-dom.html
您不能在功能组件上使用 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>
)
}