2016-11-09 21 views
3

了解handling events in React,可以有人如何绑定在两种情况下工作?如果您可以使用this.handleClick参考​​,为什么还需要绑定它?处理程序中的this不会指向组件,因为它是调用处理程序的组件?另外,为什么将处理程序放在一个匿名函数中也可以工作?如何将事件处理程序放入React修补程序中的匿名函数中绑定问题?

你必须在JSX回调中小心这个含义。在 JavaScript中,类方法默认没有绑定。如果您忘记 将this.handleClick绑定并将其传递给onClick,则在实际调用该函数时,这将是未定义的 。

解决的办法是这样的:

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

但为什么这个也行?

class LoggingButton extends React.Component { 
    handleClick() { 
    console.log('this is:', this); 
    } 

    render() { 
    // This syntax ensures `this` is bound within handleClick 
    return (
     <button onClick={(e) => this.handleClick(e)}> 
     Click me 
     </button> 
    ); 
    } 
} 
+0

我建议阅读的是如何'this'工作的更广泛的解释:https://github.com/getify/You-Dont-Know-JS/blob/71be65de0f5de05336ec97cd33e704a9b6074663/this%20%26%20object% 20原型/ README.md。那么它应该清楚。 –

回答

4

由于箭头的功能(这是该你的情况:(e) => this.handleClick(e))将自动为您“绑定” this即使你不叫上功能bind(this)。所以在这里:

<button onClick={(e) => this.handleClick(e)}> 
    Click me 
</button> 

匿名函数自动给出正确的封闭的上下文(在你的情况下,LoginButton组件),它具有​​方法。这就是它的工作方式。

通过这种方式,您还可以将此this.handleClick = this.handleClick.bind(this);转换为像这样的this.handleClick =() => this.handleClick;这样的箭头函数,并获得相同的结果。

here详细解释:

箭头功能不会创建自己的这一背景下,所以这从封闭的上下文本义。

相关问题