Can I use arrow functions in classes with ES6?

My question is very simple. If I have a class in ES6, is it possible to use the arrow function inside it?

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

The reason I'm asking is because I get an error message in my console, even when using Babel. It looks like there are many resources on the Internet that say you can do this (most of which are dedicated to developing using React).

Is this what Babylon must do and eventually become natively supported?

The error I get is an unexpected = sign, right in front of the pars.

: , , this . - - this . .

+10
3

, 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

+14

, ES6. , super , , .

, ES5, - Babel, .

question, .

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

.

0
source

Source: https://habr.com/ru/post/1017403/


All Articles