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

Is it possible to use arrow functions in classes with ES6?

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

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 应该做的事情,并且最终会得到原生支持吗?

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

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

是的,可以在 ES6 中使用箭头函数 类。我注意到您没有在构造函数中调用 super 如果您要扩展和覆盖构造函数,则必须这样做。

除了您的代码可以正确编译为 ES5 之外,请将此 link 检查到包含您的示例代码的在线 Babel 转译器。

查看与您的相似的

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

与其他人刚才的建议不同,这样做很有价值。也就是说,您的 class 函数会自动绑定 class this,而无需在构造函数中手动绑定它。

如果没有 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

是的,这是可能的。你的代码应该可以工作,你需要检查你的 Babel 设置,它的配置肯定有问题。

在您的示例中,doSomething 实际上是 class 的 属性; 属性 的类型是一个函数。这是一个额外显示方法的示例,以及 this 关键字的用法:

class SearchForm {

  doSomething = () => {
    console.log('I am a property')
  }

  doSomethingElse() {
    console.log('I am a method')
  }

  doBoth() {
    this.doSomething();
    this.doSomethingElse()
  }
}

const form = new SearchForm();
form.doBoth();

你可以现场查看here