E
E
Egor2016-02-23 07:30:24
JavaScript
Egor, 2016-02-23 07:30:24

What's the difference when declaring a function in reactjs?

Explain whether there is any difference when declaring functions, and does it somehow affect the speed of the components?

class Content extends React.Component {
  constructor() {
    super();
    this.consoleLog = () => { 
      //Первый вариант объявления
      console.log('Первый вариант');
    }
  }

    consoleLog = () => { 
    //Второй вариант объявления
    console.log('Второй вариант');
  }

  consoleLog() { 
    //Третий вариант объявления
    console.log('Третий вариант');
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2016-02-23
@DarkSir

The first and second options are very similar. The advantages over the third option are that your method will be bound to this:

class ... {
  consoleLog = () => { 
    //Второй вариант объявления
    console.log('Второй вариант');
  }

  render() {
     return (
       <button onClick={this.consoleLog} type="button"> click me </button>
     )
  }
}

In the first and second case, you won't lose this when passing the method as a callback to onClick.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question