【问题标题】:Why binding is needed in ES6 react classes为什么在 ES6 反应类中需要绑定
【发布时间】:2016-03-30 12:59:53
【问题描述】:

在新的 React ES6 类中,this 需要按此处所述绑定:http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding 例如:

class Counter extends React.Component {
  constructor() {
    super();
    this.tick = this.tick.bind(this);
  }
  tick() {
    ...
  }
  ...
}

对此的解释是因为它是默认行为,但是如果我创建一个 ES6 类然后我创建它的一个新实例 this 将被绑定

import React from 'React'

class Test extends React.Component {
    constructor() {
      super()
    }
    foo () {
      console.log('bar')
    }
    hello() {
      this.foo()
    }
}

var test = new Test()
test.hello()
// > bar

那么为什么在 React 中需要绑定呢?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您需要为方法设置this,以防万一,例如,如果您需要将函数引用传递给事件处理程序,但您不需要为每个方法设置this

    class Counter extends React.Component {
      constructor() {
        super();
        this.tick = this.tick.bind(this);
      }
    
      tick() {
        // this refers to Counter
      }
    
      fn() {
        // this refers to Counter
      }
    
      withoutBind() {
        // this will be undefined or window it depends if you use "strict mode" or not
      }
    
      render() {
    
        this.fn(); // this inside this method refers to Counter
    
        // but if you will do like this
        const fn = this.fn;
        fn(); // this will refer to global scope
    
    
        return <div>
          <button onClick={this.tick}>1</button>
          <button onClick={this.withoutBind}>2</button>
        </div>;
      }
    }
    

    Example

    【讨论】:

      【解决方案2】:

      ES6 中的类是函数。当你实例化一个类时,你会得到一个对象。对于您类中的所有方法,如果您在其中使用this,则它指的是拥有该方法的对象。

      但是当你提取方法时会令人困惑,因为上下文会发生变化。例子:

      let foo = Counter()
      foo.tick()
      

      如果调用foo.tick()this 属于对象 foo。很酷。

      但请注意:

      tickFunc = foo.tick()
      tickFunc()
      

      您已将函数与原始对象分离,现在函数调用发生在 tickFunc() 中的 this 引用全局对象的位置。

      那么为什么需要在 React 中绑定方法呢?您这样做是因为大多数时候我们将方法 references 传递给事件处理程序或作为组件的道具。当你传递你的方法的引用时,它们变成了分离的函数并且它们的上下文发生了变化。为了解决这个问题,您可以在构造函数中使用bind()

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 2016-12-21
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 2016-02-02
      相关资源
      最近更新 更多