为什么ES6反应类需要绑定 [英] Why binding is needed in ES6 react classes

查看:80
本文介绍了为什么ES6反应类需要绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In new React ES6 classes this needs to be binded as stated here: 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() {
    ...
  }
  ...
}

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

The explanation for this is because it's the default behaviour, however if I make an ES6 class and then I make a new instance of it this will be binded

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

Why binding is needed in React then?

推荐答案

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

You need set this to methods in case, for example, if you need pass function reference to event handlers, however you don't need set this for every method.,

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

示例

这篇关于为什么ES6反应类需要绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆