[英]React setState nested object callback
I have a parent component:我有一个父组件:
class ParentComponent extends React.Component {
constructor() {
super();
this.state = {
filterInputs: {
priceMin: "",
priceMax: ""
// and many other similar nested fields
}
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
this.setState((prevState) => ({
filterInputs: {
...prevState.filterInputs,
[e.target.name]: e.target.value
}
}))
}
//render method omitted
}
I also have a deeper nested child component:我还有一个更深的嵌套子组件:
class GrandchildComponent extends React.Component {
handleChange = e => {
this.props.handleChange && this.props.handleChange(e)
};
render() {
return (
<div>
<InputText id="priceMin"
value={this.props.filterInputs.priceMin}
name="priceMin"
onChange={this.handleChange}
/>
<InputText id="priceMax"
value={this.props.filterInputs.priceMax}
name="priceMax"
onChange={this.handleChange}
/>
//And many other similar input fields
</div>
)
}
}
(I tried to keep the code as minimal as possible) (我尽量减少代码)
I have a situation where the user is filling in some input fields and I am trying to send the inputs up to my parent component using a callback method handleChange
.我有一种情况,用户正在填写一些输入字段,我正在尝试使用回调方法将输入发送到我的父组件
handleChange
。 I am getting an error: TypeError: Cannot read property 'name' of null
, and the console says: Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property ``target`` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().
我收到一个错误:
TypeError: Cannot read property 'name' of null
,控制台显示: Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property ``target`` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property ``target`` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().
The problem seems to be in my handleChange
method, but I am not sure how to fix it.问题似乎出在我的
handleChange
方法中,但我不确定如何解决。
just use只需使用
this.setState({
filterInputs: {
...this.state.filterInputs,
[e.target.id]: e.target.value,
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.