【发布时间】:2022-06-15 16:29:16
【问题描述】:
我一直在阅读文档并练习 React 文档中的一些东西,直到我最终进入事件处理部分。但我不明白为什么在类组件中使用方法时我们必须绑定函数,谁能解释一下?例如:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
【问题讨论】:
-
将
this绑定到this.handleClick- 因为没有它,事件处理程序中的this将是click发生的元素
标签: javascript reactjs