【问题标题】:Is it possible to use arrow functions in classes with ES6?是否可以在 ES6 的类中使用箭头函数?
【发布时间】:2017-10-20 05:25:41
【问题描述】:

我的问题很简单。如果我在 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 绑定到该函数。我正在尝试寻找一种更好的方法来做到这一点。

【问题讨论】:

  • 不,事情不是这样运作的。正确的做法是 sample 提供的 constructor() {}。
  • 只是出于好奇,您为什么要这样做?有什么好处?
  • 使用 React 开发并希望在不显式绑定的情况下使用 this 关键字。
  • 另见stackoverflow.com/questions/31362292/… - 可能重复的问题
  • 不要将箭头函数用于您希望this 指向对象实例的方法。箭头函数定义将使用词法this,而不是对象this。这只是对箭头功能的滥用。它不仅仅是一种语法快捷方式——它以一种几乎不适合所有方法定义的方式更改了this 的值。声明方法时,箭头函数只是工作的错误工具。

标签: javascript class ecmascript-6 arrow-functions


【解决方案1】:

为此,您需要添加 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
  }
}

这里和文章很好地解释了它(除其他外) 简而言之:https://medium.com/@joshblack/writing-a-react-component-in-es2015-a0b27e1ed50a

【讨论】:

  • 这是我在你回答之前得出的确切结论,我希望 this 引用类的原因是我可以使用 'this.setState' 并引用类本身。跨度>
  • 没错。这是一个相当典型的 React 组件模式
  • 稍微偏离主题,但在同一个类中定义了一个对象,即在类中有 state = { ... }。这是另一个实验性功能,与在构造函数中使用 this.state = { ... } 有何不同?
  • 不确定。您能否更新您的代码示例以显示它?
  • @jfriend00 在使用 React 时,我想用它来修改类本身,即访问 this.state 并能够访问组件状态。我不确定你所说的对象实例是否适用于这里?
【解决方案2】:

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

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

查看与您类似的question

【讨论】:

  • 即使在调用 super() 时我仍然会遇到语法错误,它仅在使用 Babel 的“transform-class-properties”插件时才有效,不知道为什么 Babel 在线转译器会工作,除非它已经考虑到这一点并使用插件?
【解决方案3】:

是的,这是可能的。您的代码应该可以工作,您需要检查您的 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

【讨论】:

  • 这个答案没有解决任何关于使用箭头函数来定义问题的方法。
猜你喜欢
  • 2019-02-24
  • 2021-04-26
  • 2015-07-30
  • 2018-06-28
  • 2018-08-01
  • 2015-12-18
相关资源
最近更新 更多