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

泄露秘密 提交于 2019-12-05 01:25:06

In order to do that, you'll need to add the transform-class-properties babel plugin, which allows you to have auto-bound class methods like you are attempting.

Unlike what others have just suggested, there IS value in doing this. Namely, your class function automatically has the class this bound to it, without having to manually bind it in your constructor.

Without the transform-class-properties plugin, you could do:

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
  }
}

With the plugin:

export default class SearchForm extends Component {

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

Heres and article that explains it (among other thing) fairly well and consisely: https://medium.com/@joshblack/writing-a-react-component-in-es2015-a0b27e1ed50a

Tekeste Kidanu

Yes it is possible to use arrow functions inside ES6 classes. I noticed that you are not calling super inside your constructor you have to do that if you are extending and overriding the constructor.

Other than that your code compiles correctly to ES5, checkout this link to the online Babel transpiler that contains your sample code.

Checkout this question similar to yours.

Yes, it is possible. Your code should work, you need to check you Babel setup, there must be something wrong with how it's configured.

In your example, doSomething is actually a property of the class; the type of the property is a function. Here's an example that additionally shows a method, as well as a use of the this keyword:

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();

You can check it out live here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!