我是第一次使用ES6类与React,之前我一直将我的方法绑定到当前对象(如第一个示例所示),但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);
}
因此,如果我将 SomeClass.handleInputChange
传递给例如 setTimeout
,它将作用于类实例范围内,而不是 window
对象。
this
绑定也可以实现这个吧? - user16037629handleInputChange = (val) => { console.log('selectionMade: ', val); }
- Aamer Shahzad