假设您有一个子组件,它返回多个输入字段并接受 数据对象作为 Prop 。
class InputFields extends React.Component {
render() {
let data = this.props.data
return (
<div className='input-group'>
<input type='text' defaultValue={data.name} onChange={this.props.update} />
<input type='text' defaultValue={data.age} onChange={this.props.update} />
<input type='text' defaultValue={data.email} onChange={this.props.update}/>
</div>
)
}
}
父组件可能看起来像:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
items: getItemsFromSomewhere()
}
}
update(event) {
/* Somehow update main state here? */
}
render() {
/* imagine this as an array of objects, each with name, age, email ,etc. */
var items = this.state.items.map(item => {
return <InputFields data={item} update={this.update.bind(this)} />
})
return <div className='itemLists'> {items} </div>
}
}
在this.props.update
中,我想为传递下来的data
对象设置相应的状态。但 onChange
函数仅接收合成事件,该事件仅提供对 DOM 元素本身的引用。
查找需要更新哪个状态字段的最佳方法是什么,例如,当 data.name
的输入字段更改时,如何将其传播到主父级中的状态?
我知道可以使用 refs
,但是我如何知道在更改事件上要抓取哪个 ref
?我只需要遍历所有这些吗?
最佳答案
你可以这样做:
class InputFields extends React.Component {
_onChange(field) {
this.props.update(field, this.props.data);
}
render() {
let data = this.props.data
return (
<div className='input-group'>
<input type='text' defaultValue={data.name} onChange={this._onChange.bind(this, 'name')} />
<input type='text' defaultValue={data.age} onChange={this._onChange.bind(this, 'age')} />
<input type='text' defaultValue={data.email} onChange={this._onChange.bind(this, 'email')}/>
</div>
)
}
}
然后在父组件的 update
函数中,您将更改的字段作为字符串加上整个数据对象:
update(field, item) {
// do stuff
var value = item[field];
}
关于javascript - 将状态更改从 onChange 事件传递给父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924095/