有一个lot关于在 ES6 React 中处理绑定的多种方法所写的问题/文章,但大多数似乎都没有解决 中概述的问题反应文档 https://facebook.github.io/react/docs/reusable-components.html (emphasis mine):
我们建议您在构造函数中绑定事件处理程序,以便每个实例只绑定一次:
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@自动绑定装饰器 https://github.com/jayphelps/core-decorators.js#autobind在类级别作为一个简单的解决方案:
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
我不明白的是:这个装饰器是否会具有与内联绑定方法相同的缺点?即,每个实例的方法只会绑定一次吗?
如果没有,是否有一个简洁的解决方案可以避免这个陷阱?
类实例字段 https://github.com/tc39/proposal-class-public-fields及其关联的初始化器解决了必须分配与构造函数内的方法同名的属性的问题,但语法更简洁。下面的例子可以用 Babel 来实现类属性变换 https://babeljs.io/docs/plugins/transform-class-properties/:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
tick = () => {
this.setState({count: this.state.count + 1});
};
...
}
这创建了一个新的、绑定的tick
每个人的财产Counter
实例。这创造了the same绑定函数的数量为React.createClass
did.
如果没有实例字段和初始值设定项,效果是相同的(绑定tick
为每个创建属性Counter
实例),但语法更详细:
constructor(props) {
super(props);
this.state = {count: props.initialCount};
this.tick = this.tick.bind(this);
}
tick() {
this.setState({count: this.state.count + 1});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)