为什么ES6反应类需要绑定

时间:2016-03-30 12:59:54

标签: javascript reactjs

在新的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需要绑定呢?

2 个答案:

答案 0 :(得分: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>;
  }
}

Example

答案 1 :(得分:0)

ES6中的类是函数。实例化类时,会得到一个对象。你的类中的所有方法,如果你在其中使用float [ ] getLineEquation( int [ ] line) { float [ ] equation = new float [3]; int dx = line[2] - line[0]; int dy = line[3] - line[1]; equation[0] = -dy; equation[1] = dx; equation[2] = dy*line[0] - dx*line[1]; return equation; } ,它指的是拥有该方法的对象。

但是由于上下文发生了变化,因此在提取方法时会让人感到困惑。例子:

this

如果您致电let foo = Counter() foo.tick() foo.tick()属于对象foo。凉。

但请注意:

this

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

那你为什么需要在React中绑定你的方法呢?你这样做是因为大多数时候我们将方法引用传递给事件处理程序或作为组件的道具。传递方法的引用时,它们将成为分离的函数及其上下文更改。要解决此问题,请在构造函数中使用tickFunc()

相关问题