gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:16:43 27 4
gpt4 key购买 nike

我是使用 ES6 类和 React 的新手,以前我一直将我的方法绑定(bind)到当前对象(在第一个示例中显示),但是 ES6 是否允许我将类函数永久绑定(bind)到带有箭头的类实例? (在作为回调函数传递时很有用。)当我尝试像使用 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 对象。

最佳答案

你的语法有点不对劲,只是在属性名后面少了一个等号。

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

这是一项实验性功能。您需要在 Babel 中启用实验性功能才能编译它。 Here是一个启用了实验的演示。

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

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

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


关于javascript - 如何使用箭头函数(公共(public)类字段)作为类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31362292/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com