为什么ES6反应类需要绑定

bar*_*zag 6 javascript reactjs

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

class Counter extends React.Component {
  constructor() {
    super();
    this.tick = this.tick.bind(this);
  }
  tick() {
    ...
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

对此的解释是因为它是默认行为,但是如果我创建一个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
Run Code Online (Sandbox Code Playgroud)

为什么React需要绑定呢?

Ale*_* T. 5

您需要设置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>;
  }
}
Run Code Online (Sandbox Code Playgroud)

Example