gpt4 book ai didi

javascript - 是否可以在 ES6 的类中使用箭头函数?

转载 作者:可可西里 更新时间:2023-11-01 02:36:47 25 4
gpt4 key购买 nike

我的问题很简单。如果我在 ES6 中有一个类,是否可以在其中使用箭头函数?

import React, { Component } from 'react';

export default class SearchForm extends Component {

state = {
searchText: ''
}

onSearchChange = e => {
this.setState({ searchText: e.target.value });
}

handleSubmit = e => {
e.preventDefault();
this.props.onSearch(this.query.value);
e.currentTarget.reset();
}

render() {
return (
<form className="search-form" onSubmit={this.handleSubmit} >
<label className="is-hidden" htmlFor="search">Search</label>
<input type="search"
onChange={this.onSearchChange}
name="search"
ref={(input) => this.query = input}
placeholder="Search..." />
<button type="submit" id="submit" className="search-button">
<i className="material-icons icn-search">search</i>
</button>
</form>
);
}
}

我问的原因是我的控制台出现错误,即使使用 Babel 也是如此。似乎互联网上有很多资源表明您可以做到这一点(其中大部分是关于使用 React 进行开发的)。

这是 Babel 应该做的事情,并且最终会得到原生支持吗?

我得到的错误是一个意外的 = 符号,就在括号之前。

编辑: 我忘了说,我想这样做的原因是为了在类的上下文中使用 this 关键字。如果我使用常规函数 - 据我所知 - 我将不得不将 this 绑定(bind)到该函数。我正在尝试寻找一种更好的方法来做到这一点。

最佳答案

为此,您需要添加 transform-class-properties babel 插件,它允许您像您尝试的那样拥有自动绑定(bind)的类方法。

与其他人刚刚建议的不同,这样做是有值(value)的。也就是说,您的类函数会自动将类 this 绑定(bind)到它,而无需在您的构造函数中手动绑定(bind)它。

如果没有 transform-class-properties 插件,您可以:

export default class SearchForm extends Component {

constructor(props) {
super(props)
this.doSomething = this.doSomething.bind(this)
}

doSomething () {
console.log(this) // <-- 'this' is the class instance
}
}

使用插件:

export default class SearchForm extends Component {

doSomething = () => {
console.log(this) // <-- 'this' is the class instance, no binding necessary
}
}

Heres 和文章很好地解释了它(除其他外)一致地:https://medium.com/@joshblack/writing-a-react-component-in-es2015-a0b27e1ed50a

关于javascript - 是否可以在 ES6 的类中使用箭头函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44080928/

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