这是一个针对 ES 的新提案(类字段),处于 [阶段 3][1]
现在。要运行以这种方式编写的代码,您需要一个转译器
比如 Babel 和一个合适的插件。
转译前:
class A {
static color = "red";
counter = 0;
handleClick = () => {
this.counter++;
}
}
编译后(在 Babel Repl 上使用第 2 阶段):
class A {
constructor() {
this.counter = 0;
this.handleClick = () => {
this.counter++;
};
}
}
A.color = "red";
除了官方提出的[2ality blog post][2]是一个不错的
来源以查看详细信息。
如果您有时间阅读讨论,这里是 [reddit 帖子][3]
风暴这个提议背后的原因是什么:)
这里的箭头函数是另一回事。您可以使用实例
没有构造函数的属性并将您的代码与标准混合
职能。但是当你想使用类似 this 的东西时不会
工作:
class App extends React.Component {
state = { bar: "baz"}
foo() { console.log(this.state.bar) };
render() {
return <div><button onClick={this.foo}>Click</button></div>;
}
}
我们需要以某种方式绑定我们的函数:
return <div><button onClick={this.foo.bind(this)}>Click</button></div>
但是,将我们的函数绑定在 JSX 属性中并不是那么好,因为它会
在每个渲染中创建我们的函数。
在我们的构造函数中很好地绑定的一种方法:
constructor(props) {
super(props);
this.foo = this.foo.bind( this );
}
但是,如果我必须编写一个构造函数,那有什么意义呢?这就是为什么
您在我们定义类的任何地方都可以看到箭头函数
你的第二个例子。由于箭头,无需绑定功能
职能。但这与我的这个新提案没有直接关系
思考。
[1]:https://github.com/tc39/proposal-class-fields[2]:
http://2ality.com/2017/07/class-fields.html [3]:
https://www.reddit.com/r/javascript/comments/6q0rov/es_proposal_class_fields/