在新的React ES6中,类this需要按如下所述进行绑定:http : //facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding 例如:
this
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中需要绑定呢?
你需要设置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