2017-10-21 57 views
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'对象,因为它已经可以引用组件本身了?

+0

因为什么'this'是在事件处理程序(通常调度该事件的对象 - 在你的代码,它会是'button'元素) –

+0

同样,你的代码会导致'isToggleOn'最初为'true',然后是''ON''或'OFF'' - 因此,总是“truthy” - 看起来很奇怪 –

回答

2

你是对的,但你错过了一件事。没有绑定到处理程序的组件this的范围。那么当你想要事件的上下文时会发生什么?你没有它。

解决此问题的另一种方法是从词汇上绑定组件,以便您不必担心手动绑定每个函数。

handleClick =() => { //arrow function applied 
    this.setState(prevState => ({ 
     isToggleOn: !prevState.isToggleOn 
    })); 
} 

请注意,现在您现在不再需要组件构造函数了。

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); 
} 

现在变得

state = {isToggleOn: true}; 
相关问题