为什么在ES6-react类中需要绑定
Why binding is needed in ES6 react classes
在新的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中需要绑定?
您需要将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
ES6中的类是函数。当你实例化一个类时,你会得到一个对象。对于类中的所有方法,如果在其中使用this
,则它引用拥有该方法的对象。
但是,由于上下文的变化,提取方法时会令人困惑。示例:
let foo = Counter()
foo.tick()
如果调用foo.tick()
,则this
属于对象foo。凉的
但请注意:
tickFunc = foo.tick()
tickFunc()
您将函数与原始对象分离,现在函数调用发生在tickFunc()
中的this
引用全局对象的位置。
那么,为什么你需要在React中绑定你的方法呢?之所以这样做,是因为大多数时候我们将方法引用传递给事件处理程序或作为组件的道具。当您传递方法的引用时,它们会变成分离的函数,并且它们的上下文会发生变化。要解决这个问题,可以在构造函数中使用bind()
。
相关文章:
- react.js中的密钥绑定
- react组件中的绑定方法
- 在React中,为什么我必须绑定onClick函数而不是调用它
- 使用react router/react router redux将特定的redux操作绑定到一个路由
- 是否可以为React'打开React.js自动绑定;s类模型
- 使用Re-base时,在React中从状态绑定和取消绑定Firebase
- ES6/React第二项绑定失败
- 为什么在ES6-react类中需要绑定
- 当函数绑定在构造函数中时,如何在 ES6 React 中向事件处理程序添加参数
- 将 Picker 绑定到 React Native 中的 Picker.Item 列表
- ReactFire-获取'对象作为React子对象无效'将Firebase绑定到React状态时
- 将一个值传递给绑定的React JS文件
- 如何强制React ES6静态方法's '绑定到词法范围
- React.js ES6避免绑定'this'每一种方法
- 为什么我必须为React组件类中定义的方法绑定(this),而不是在常规ES6类中
- React Native:不能读取property 'push'让NavigatorIOS和ES6绑定(
- React.js和ES6:没有在构造函数中绑定函数的任何理由
- React 中的哪种绑定上下文方法(ES6 类)更好
- 将状态绑定到 React 中映射函数内部的条件语句
- 在 constructor() 中绑定许多 React 组件方法的上下文的正确约定是什么?