【问题标题】:How does placing an event handler in an anonymous function in React fix bind issues?在 React 的匿名函数中放置事件处理程序如何解决绑定问题?
【发布时间】:2016-11-09 01:07:34
【问题描述】:

了解handling events in React,其他人可以在以下两种情况下如何绑定吗?如果可以引用handleClickthis.handleClick,为什么还需要绑定呢?处理程序内部的this 不会已经指向组件,因为它是调用处理程序的组件吗?另外,为什么将处理程序放在匿名函数中也可以?

在 JSX 回调中你必须小心 this 的含义。在 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>
    );
  }
}

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

因为箭头函数(在你的情况下是:(e) =&gt; this.handleClick(e))会自动为你“绑定”this,即使你没有在函数上调用bind(this)。所以这里:

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

匿名函数自动获得正确的封闭上下文(在您的情况下为 LoginButton 组件),并且它具有 handleClick 方法。这就是它的工作方式。

这样你也可以把this.handleClick = this.handleClick.bind(this);变成像this.handleClick = () =&gt; this.handleClick;这样的箭头函数,得到同样的结果。

详细解释看here

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

【讨论】:

    【解决方案2】:

    在 javascript 中,“this”是动态范围的。这意味着handleClick 中的“this”会根据谁调用它而变化。它不受任何上下文的约束。当您在 Login 类中定义它时,“this”指的是 Login 类。那么你在 jsx 世界中使用 handleClick inside 按钮。此时,问问自己是谁在打电话给handleClick()?答案是 jsx 中的按钮元素,现在handleClick 中的“this”指的是按钮元素。那么这里发生了什么:

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

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

    如果你这样写

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

    “this”总是指 myObject

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      相关资源
      最近更新 更多