如何使用箭头函数(公共类字段)作为类方法? [英] How to use arrow functions (public class fields) as class methods?
问题描述
我是在 React 中使用 ES6 类的新手,之前我一直将我的方法绑定到当前对象(显示在第一个示例中),但是 ES6 是否允许我使用箭头将类函数永久绑定到类实例?(在作为回调函数传递时很有用.)当我尝试在 CoffeeScript 中尽可能使用它们时出现错误:
class SomeClass 扩展 React.Component {//而不是这个构造函数(){this.handleInputChange = this.handleInputChange.bind(this)}//我能以某种方式做到这一点吗?我只是语法错误吗?handleInputChange (val) =>{console.log('selectionMade: ', val);}
这样,如果我将 SomeClass.handleInputChange
传递给例如 setTimeout
,它的范围将限定为类实例,而不是 window
对象.
你的语法有点不对,只是在属性名称后缺少一个等号.
class SomeClass 扩展 React.Component {handleInputChange = (val) =>{console.log('selectionMade: ', val);}}
这是一项实验性功能.你需要在 Babel 中启用实验性功能才能编译它.这里 是一个启用实验的演示.
要在 babel 中使用实验性功能,您可以从此处安装相关插件.对于此特定功能,您需要 transform-class-properties
插件:
<代码>{插件":[转换类属性"]}
您可以在此处阅读有关类字段和静态属性提案的更多信息><小时>
I'm new to using ES6 classes with React, previously I've been binding my methods to the current object (show in first example), but does ES6 allow me to permanently bind a class function to a class instance with arrows? (Useful when passing as a callback function.) I get errors when I try to use them as you can with 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);
}
So that if I were to pass SomeClass.handleInputChange
to, for instance setTimeout
, it would be scoped to the class instance, and not the window
object.
Your syntax is slightly off, just missing an equals sign after the property name.
class SomeClass extends React.Component {
handleInputChange = (val) => {
console.log('selectionMade: ', val);
}
}
This is an experimental feature. You will need to enable experimental features in Babel to get this to compile. Here is a demo with experimental enabled.
To use experimental features in babel you can install the relevant plugin from here. For this specific feature, you need the transform-class-properties
plugin:
{
"plugins": [
"transform-class-properties"
]
}
You can read more about the proposal for Class Fields and Static Properties here
这篇关于如何使用箭头函数(公共类字段)作为类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!