编程语言
首页 > 编程语言> > javascript – 如何使用箭头函数(公共类字段)作为类方法?

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

作者:互联网

我刚接触使用带有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);
  }

因此,如果我将SomeClass.handleInputChange传递给,例如setTimeout,它将作用于类实例,而不是窗口对象.

解决方法:

您的语法略有偏差,只是在属性名称后面缺少等号.

class SomeClass extends React.Component {
  handleInputChange = (val) => {
    console.log('selectionMade: ', val);
  }
}

这是一个实验性功能.您需要在Babel中启用实验性功能才能进行编译. Here是启用实验的演示.

要在babel中使用实验性功能,您可以从here安装相关插件.对于此特定功能,您需要transform-class-properties plugin

{
  "plugins": [
    "transform-class-properties"
  ]
}

您可以阅读有关类字段和静态属性here的提案的更多信息

标签:ecmascript-next,javascript,ecmascript-6,reactjs,babeljs
来源: https://codeday.me/bug/20190911/1803137.html