是否可以在ES6的类中使用箭头功能?

tom*_*hes 10 javascript class ecmascript-6 arrow-functions

很简单,如果我在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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我问的原因是我的控制台出现错误,即使使用Babel,虽然看起来互联网上有很多资源说明你可以做到这一点(其中大部分是关于使用React进行开发).

这是巴贝尔应该做的事情,并最终会得到本地支持吗?

我得到的错误是意外=符号,就在parens之前.

编辑:我忘了提到,我希望这样做的原因是在Class的上下文中使用'this'关键字,如果我使用常规函数 - 对我的理解 - 我必须将'this'绑定到功能,我正在寻找一种更好的方法.

Log*_*ist 14

为了做到这一点,你需要添加transform-class-propertiesbabel插件,它允许你像你正在尝试的自动绑定类方法.

与其他人刚才建议的不同,这样做很有价值.也就是说,您的类函数自动将类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
  }
}
Run Code Online (Sandbox Code Playgroud)

随着插件:

export default class SearchForm extends Component {

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

Heres和文章解释它(以及其他内容)相当好和明确:https://medium.com/@joshblack/writing-a-react-component-in-es2015-a0b27e1ed50a