如何在React中的匿名函数中放置事件处理程序修复绑定问题?

时间:2016-11-09 01:07:34

标签: javascript reactjs ecmascript-6

了解handling events in React,其他人可以在下面的两个场景中如何运作?如果您可以使用handleClick引用this.handleClick,为什么还需要绑定它?处理程序中的this不会指向该组件,因为它是调用处理程序的组件吗?另外,为什么将处理程序放在匿名函数中也有效?

  

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

2 个答案:

答案 0 :(得分:4)

因为箭头功能(在你的情况下这是(e) => this.handleClick(e))会自动&#34;绑定&#34;即使您没有在功能上拨打this,也可以bind(this)为您服务。所以这里:

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

匿名函数会自动给出正确的封闭上下文(您的案例中为LoginButton组件),并且它具有handleClick方法。这就是它的工作方式。

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

查看here以获取详细说明:

  

箭头函数不会创建自己的上下文,因此这具有封闭上下文的原始含义。

答案 1 :(得分:0)

在javascript中,“ this”是动态范围的。这就是说,handleClick中的“ this”根据谁调用而改变。它不受任何上下文的约束。当您在Login类中定义它时,“ this”是指Login类。那么您在jsx世界中使用handleClick内部按钮。此时,问问自己谁在呼叫handleClick()?答案是jsx中的按钮元素,现在handleClick中的“ this”是指按钮元素。所以这里发生了什么:

 this.handleClick = this.handleClick.bind(this)//(this) refers to class Login.

bind()方法返回一个新函数,并设置“ this”的上下文。在这种情况下,我们是说this.handleClick从现在开始是一个不同的功能。其“ this”值将始终引用类Login

如果您这样写

this.handleClick = this.handleClick.bind(myObject); 

“ this”将始终引用myObject

如果在箭头函数中使用“ this”,则“ this”将在词法范围内,换句话说在本地范围内。这意味着无论您在哪里调用箭头handleClick(),箭头函数内部的“ this”将始终引用其创建的上下文,在您的示例中为Login Class。