最近,我开始修补React.js,我喜欢它。我开始使用常规的ES5,以便掌握所有内容,所有文档均使用ES5编写…
但是现在我想尝试一下ES6,因为它有光泽而且是新的,而且似乎确实简化了某些事情。让我感到困扰的是,对于我添加到组件类中的每个方法,现在都必须将“ this”绑定到该方法,否则它将无法正常工作。所以我的构造函数最终看起来像这样:
constructor(props) { super(props); this.state = { ...some initial state... } this.someHandler = this.someHandler.bind(this); this.someHandler = this.someHandler.bind(this); this.someHandler = this.someHandler.bind(this); this.someHandler = this.someHandler.bind(this); this.someHandler = this.someHandler.bind(this); this.someHandler = this.someHandler.bind(this); this.someHandler = this.someHandler.bind(this); }
如果我要在类中添加更多方法,这将变得更大,更难看。
我的问题是,是否有某种方法可以解决此问题,或者至少使其更容易,更短且更不丑陋?我想在React中使用ES6的主要原因之一是使我的代码更简洁,但这却相反。任何建议或意见将不胜感激。
您可以使用类字段在构造函数外部进行绑定。它们如下所示:
class Foo extends React.Component { handleBar = () => { console.log('neat'); }; handleFoo = () => { console.log('cool'); }; render() { return ( <div onClick={this.handleBar} onMouseOver={this.handleFoo} /> ); } }
Babel通过其类属性转换实验性地支持了类字段,但是它们仍然是“实验性的”,因为它们是Stage 3 Draft(尚未在Babel预设中)。
您将需要手动进行绑定,直到ES7或启用Babel中的功能为止。Babel在React on ES6 +上的博客文章对此主题进行了简要介绍。