我正在编写一个 React 应用程序,但出于某种原因,我无法解决这个问题。下面是一个片段,唯一需要的是:
onFirstNameChange(event: any){
console.log(event.target.value)
// this.setState({
// firstname: event.target.value
// })
}
注释掉的代码不会运行,它说它无法读取未定义的属性。但是,当我记录事件值时,它会完美地完成。关于为什么会发生这种情况的任何想法?这是一个 onchange 事件。它也是深度嵌套的,但是它的值(value)确实让它回来了。
最佳答案
用 ES6 类编写的 React 组件,不会将 this
自动绑定(bind)到组件的方法。主要有2 种解决方案。您可以选择使用:
要么在构造函数中显式绑定(bind)this
constructor(props) {
super(props);
// rest of code //
this.state = {
firstname: '',
};
// rest of code //
this.onFirstNameChange = this.onFirstNameChange.bind(this);
}
或者使用 ES6 箭头函数
onFirstNameChange = (event: any) => {
console.log(event.target.value);
this.setState({
firstname: event.target.value
});
}
关于javascript - 使用 setState 时 React TypeScript 回调读取未定义,但它会记录该值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69368172/