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

时间:2017-05-20 01:11:01

标签: 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>
    );
  }
}
&#13;
&#13;
&#13;

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

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

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

编辑:我忘了提及,我希望这样做的原因是为了利用这个&#39;这个&#39;关键字在Class的上下文中,如果我使用常规函数 - 根据我的理解 - 我必须绑定&#39;这个&#39;对于这个功能,我试图寻找一种更好的方法。

3 个答案:

答案 0 :(得分:14)

为了做到这一点,你需要添加transform-class-properties babel插件,它允许你像你正在尝试的那样使用自动绑定的类方法。

与其他人刚刚建议的不同,这样做有价值。也就是说,您的类函数自动绑定了类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

答案 1 :(得分:0)

是的,可以在ES6课程中使用箭头功能。我注意到,如果要扩展和覆盖构造函数,则不要在构造函数中调用public class MenuController { @FXML public void SendSubject(ActionEvent e) throws IOException, SQLException { DB_Connection connection = new DB_Connection(); connection.addSubject("English"); } } ,而是必须这样做。

除了您的代码正确编译到ES5之外,请将此link结帐到包含示例代码的在线Babel转发器。

结帐此question与您的相似。

答案 2 :(得分:0)

是的,有可能。您的代码应该有效,您需要检查Babel设置,它的配置方式一定有问题。

在您的示例中,doSomething实际上是该类的属性;属性的类型是一个函数。这是一个示例,它还显示了一个方法,以及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

相关问题