我有一个父级组件:
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
}
我还有一个更深层的嵌套子组件:
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>
)
}
}
(我试图将代码尽量减少)
我遇到一种情况,用户正在填写一些输入字段,并且我试图使用回调方法handleChange
将输入发送到我的父组件。
我收到错误消息: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().
问题似乎出在我的handleChange
方法中,但我不确定如何解决。
答案 0 :(得分:1)
只需使用
this.setState({
filterInputs: {
...this.state.filterInputs,
[e.target.id]: e.target.value,
}
});