【发布时间】:2015-11-18 11:44:46
【问题描述】:
最近,我开始修改 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);
}
如果我要在我的类中添加更多方法,这将变得更大、更丑陋。
我的问题是,有没有办法解决这个问题,或者至少让它更容易、更短、更丑?我想用 ES6 尝试 React 的主要原因之一是让我的代码更简洁,但这恰恰相反。任何建议或意见将不胜感激。
【问题讨论】:
-
你真的在某处使用所有方法作为处理程序吗?
-
嗯,这是从更高级别的组件中获取的,所以是的,它们都在层次结构的某个地方使用。我试图遵循他们的理念,并试图最好地弄清楚哪个组件需要知道什么,这就是我最终得到的。
-
但是它们不是(不应该)作为组件对象上的方法调用,而不是作为函数传递吗?
-
我个人为此使用装饰器 (specifically
autobind) 而不是类属性初始化器。
标签: javascript reactjs ecmascript-6