【发布时间】:2016-10-05 09:09:29
【问题描述】:
有很多关于在 ES6 React 中处理绑定的多种方法的问题/文章,但大多数似乎都没有解决React docs 中概述的问题(强调我的):
我们建议您在构造函数中绑定事件处理程序,以便 每个实例只绑定一次:
constructor(props) { super(props); this.state = {count: props.initialCount}; this.tick = this.tick.bind(this); }
对于上下文,他们建议不要对方法进行内联绑定,例如:
//using .bind()
<div onClick={this.tick.bind(this)}>
// ES6 anon arrow functions
<div onClick={() => this.tick()}>
// ES.Next :: operator
<div onClick={::this.tick}>
当然。但是在构造函数中绑定每个方法的推荐解决方案是繁琐的/很多方法,所以我在看 ES.Next @autobind decorator 在班级级别作为一个简单的解决方案:
import { autobind } from 'core-decorators';
@autobind
class Person {
getPerson() {
return this;
}
getPersonAgain() {
return this;
}
}
let person = new Person();
let { getPerson, getPersonAgain } = person;
getPerson() === person;
// true
getPersonAgain() === person;
// true
我想不通的是:这个装饰器会和内联绑定方法有同样的缺点吗?即,每个实例的方法是否只绑定一次?
如果没有,是否有避免这种陷阱的简洁解决方案?
【问题讨论】:
-
仅供参考的 ES7 不会有装饰器:2ality.com/2016/01/ecmascript-2016.html
-
这可能会出现在未来的版本中,但不会出现在 ES7(已经完成)中。请阅读标签维基!我更新了你的问题。
标签: javascript reactjs ecmascript-6 ecmascript-next