0
在这里这个例子中,我们需要handleClick()的“这个”对象绑定到全局范围:为什么我们需要绑定“这”的JSX回调
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>
);
}
}
然而,handleClick()是在组件的范围内定义的,所以我们不应该不需要为这个函数指定'this'对象,因为它已经可以引用组件本身了?
因为什么'this'是在事件处理程序(通常调度该事件的对象 - 在你的代码,它会是'button'元素) –
同样,你的代码会导致'isToggleOn'最初为'true',然后是''ON''或'OFF'' - 因此,总是“truthy” - 看起来很奇怪 –