What is the difference between function statements (React)?

Asked

Viewed 121 times

3

I am learning Act and 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 summary is a button that when clicking displays a message. But one thing I didn’t understand is this statement from handleClick, For if I so pronounce:

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

The compilation does not give error, but clicking gives the following error. I am not sure the purpose of this statement. Someone could clarify this doubt?

inserir a descrição da imagem aqui

  • Read the tutorial again, it looks like you skipped a step. Is this? https://reactjs.org/docs/react-without-es6.html

  • Yes, I’m reading, but I’m not getting to know the difference between declaring as handleClick(){}; and handleClick = () => {};.

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 https://reactjs.org/docs/handling-events.html, a solution is to force bind in the Test construct:

constructor(props) {
   super(props);
   this.state = { message: 'Hello!' };
   this.handleClick = this.handleClick.bind(this);
}
  • I understood this different statement does exactly what the line you added did.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.