React Error无法读取未定义的属性“ onChange”
该应用程序类正在调用Breakpoint组件的映射
<Breakpoints key={breakpoint.key}
name={breakpoint.name}
minWidth={breakpoint.minWidth}
onChange={function () { // this is where react says my error is
this.onChange(breakpoint)
}.bind(this)}/>
这是父方法
`onChange(breakpoint) {
this.props.breakpoints[breakpoint.key].name = name;
this.state (this.state);
console.log(breakpoint)
}`
这些是子元素
<input type="text" name="name" defaultValue={this.state.name} onBlur={this.onChange}/>
<input type="text" name="minWidth" defaultValue={this.state.minWidth} onBlur={this.onChange}/>
这就是我观察并尝试更新代码的方式
onChange(e) {
e.preventDefault();
this.setState(
{[e.target.name]: e.target.value},
function () {
console.log(this.state.name);
this.props.onChange({
key: this.state.key,
name: this.state.name,
minWidth: this.state.minWidth
});
}
);
}
最佳答案
失败在于我相信的最后一个代码片段,请参阅我添加的注释行:
onChange(e) {
e.preventDefault();
this.setState(
{[e.target.name]: e.target.value},
function () {
// HERE: "this" is newly created for this function, so this.props is undefined, so this.props.onChange fires an error
console.log(this.state.name);
this.props.onChange({
key: this.state.key,
name: this.state.name,
minWidth: this.state.minWidth
});
}
);
}
该修补程序既可以将该函数包装在绑定中,也可以使用es2015粗箭头函数(这需要babel转译)或用户仅使用现代浏览器。您也可以这样使用
var self = this
技巧。这是三个选项:// bind
onChange(e) {
e.preventDefault();
this.setState(
{[e.target.name]: e.target.value},
function () {
console.log(this.state.name);
this.props.onChange({
key: this.state.key,
name: this.state.name,
minWidth: this.state.minWidth
}.bind(this));
}
);
}
// es2015 arrow functions
onChange(e) {
e.preventDefault();
this.setState(
{[e.target.name]: e.target.value},
() => {
console.log(this.state.name);
this.props.onChange({
key: this.state.key,
name: this.state.name,
minWidth: this.state.minWidth
});
}
);
}
// self trick
onChange(e) {
e.preventDefault();
var self = this;
this.setState(
{[e.target.name]: e.target.value},
function () {
console.log(self.state.name);
self.props.onChange({
key: self.state.key,
name: self.state.name,
minWidth: self.state.minWidth
});
}
);
}