Doubt in the execution

Asked

Viewed 37 times

0

I am attending the basic course of Reactjs of João Ribeiro, and in class 17 he writes the following code:

class App extends React.Component {

  metodo = (texto) => {
    console.log(texto)
  }
  
  render() {
    return (
      <div>
        <button onClick={this.metodo('Olá mundo')}>Clicar</button>
      </div>
    )
  }
}
ReactDOM.render(<App /> , document.getElementById('root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>

My question is: Why the "Hello world" already appears on the console even before the click receive button?

3 answers

2

Because the property onClick should receive a function like Handler, but you are not declaring a function, you are invoking a function and passing its return to the onClick.

As the function metodo is invoked, it prints Olá mundo. If you want to invoke the function metodo while clicking, you can declare an anonymous function within the property onClick, which in turn invokes its method, as follows:

<button onClick={() => this.metodo('Olá mundo')}>Clicar</button>

2

the "method" function receives a parameter called "text"

metodo(texto)

Then, when passing the string "hello world" in the method("hello world"), it prints in the console the text itself, because the Method() calls the function console.log(text) // In the case the printed text is hello world.

This is something very basic Javascript, if you had difficulties with something simple, you will certainly have a lot of difficulty dealing with React, especially in the part of States

recommend learning the basics of JS first

Explaining functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Fun%C3%A7%C3%B5es

0

As already answered, onClick is a prop that should receive a function. You didn’t pass a function, you passed the return of a function. The difference is very clear in the example below, which I put in the Codesandbox

export default class App extends React.Component {
  metodo = texto => {
    console.log(texto);
  };

  metodoCorreto = texto => event => {
    console.log(event.target);
    console.log(texto);
  };

  render() {
    return (
      <div>
        <button onClick={this.metodo("Olá mundo")}>Clicar</button>
        <button onClick={this.metodoCorreto("Olá mundo")}>
          Clicar correto
        </button>

        <button
          onClick={event => {
            this.metodo("Olá mundo");
          }}
        >
          Clicar correto 2
        </button>
      </div>
    );
  }
}

Browser other questions tagged

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