我是在 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
,它将作用于类实例,而不是window
object.
您的语法稍有偏差,只是在属性名称后面缺少一个等号。
class SomeClass extends React.Component {
handleInputChange = (val) => {
console.log('selectionMade: ', val);
}
}
这是一个实验性功能。您需要在 Babel 中启用实验性功能才能进行编译。是一个启用实验的演示。
要使用 babel 中的实验性功能,您可以从以下位置安装相关插件here https://babeljs.io/docs/plugins/。对于此特定功能,您需要transform-class-properties plugin http://babeljs.io/docs/plugins/transform-class-properties/:
{
"plugins": [
"transform-class-properties"
]
}
您可以阅读有关类字段和静态属性提案的更多信息here https://github.com/tc39/proposal-class-fields
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)