What is the difference between function declarations (React)?

3

I'm learning react and I came across this example (which works normally):

import React, { Component } from 'react'
import './Teste.css';

class Teste extends Component {

  constructor(props) {
     super(props);
    this.state = { message: 'Hello!' };
  }


  handleClick = () => {
    alert(this.state.message);
  }

   render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          Say hello
        </button>
      </div>
    );
  }
}

export default Teste;

In short, it is a button that, when clicked, displays a message. But one thing I did not understand is this statement of handleClick , because if I declare it this way:

 handleClick () {
    alert(this.state.message);
 }

Compilation does not give error, but clicking gives the following error. I do not understand the purpose of this statement. Could someone clarify this doubt?

    
asked by anonymous 21.09.2018 / 18:13

1 answer

3

Hello,

The problem is related to the scope of this, when click event is triggered this represents the button and not the Test component.

As can be seen in link , one solution is to bind in the Test construct:

constructor(props) {
   super(props);
   this.state = { message: 'Hello!' };
   this.handleClick = this.handleClick.bind(this);
}
    
21.09.2018 / 18:31