我刚接触使用带有React的ES6类,之前我已经将我的方法绑定到当前对象(在第一个示例中显示),但ES6是否允许我使用箭头将类函数永久绑定到类实例?(当作为回调函数传递时很有用.)当我尝试使用它时,我遇到错误,就像使用CoffeeScript一样:
class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我要传递SomeClass.handleInputChange给setTimeout它,那么它将被限定为类实例,而不是window对象.
最近,我开始修补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);
}
Run Code Online (Sandbox Code Playgroud)
如果我要为我的课程添加更多的方法,这将成为一个更大,更丑陋的混乱.
我的问题是,有没有办法解决这个问题,或者至少让它变得更容易,更短,更难看?我想尝试与ES6一起使用React的主要原因之一是让我的代码更简洁,但这恰恰相反.任何建议或意见将不胜感激.