可以使用箭头函数或手动绑定方法来避免这个问题。例如,在以下代码中,使用箭头函数来确保handleChange()
中的this
引用正确的作用域:
class App extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
// 使用箭头函数来确保 `this` 引用正确的作用域
handleChange = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
Count: {this.state.count}
);
}
}
另一种解决方法是在constructor()
中手动绑定方法,并将它们分配给实例属性:
class App extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
// 手动绑定方法并将它们分配给实例属性
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
Count: {this.state.count}
);
}
}