相关疑难解决方法(0)

如何使用箭头函数(公共类字段)作为类方法?

我刚接触使用带有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.handleInputChangesetTimeout它,那么它将被限定为类实例,而不是window对象.

javascript ecmascript-6 reactjs babeljs ecmascript-next

168
推荐指数
4
解决办法
8万
查看次数