2

react component

Am I wrong if I explain the provided example like this : once the component loads, the first button will be clicked automatically because this.handleClick1 was called by adding the bracket.

If you click the second button, there will be an error because you are using an es5 function and the "this" keyword behaves differently in an ES5 function compared with the arrow function or ES6 function. In ES5 function, the "this" keyword refers directly to the object that contains it and in this case the object that contains it is the which is an object and so there is an error because the button object does not contain a handleClick1 property. To fix this problem, you have to either use an ES6 function to declare the handleClick1 function or if you must use the ES5 function then you have to bind the function to the class

  • 3
    Please post code as text, not as a painting. – Bergi Dec 19 '21 at 17:45
  • 1
    There is no such thing as a "ES5 function" or "ES6 function", they're all just functions with different syntaxes. And notice that you didn't even use the `function` keyword. – Bergi Dec 19 '21 at 17:48

1 Answers1

1

The first button is not clicked immediately. You are calling the handler function immediately instead of assigning it as the handler.

Arrow functions and .bind() act similar in that they statically bind this for that function.

However, React.Component won't statically bind methods to itself. If you (properly) set a button onClick to a component method, the context will change. To fix this somewhat unexpected behavior you will need to use arrow functions or .bind() in the constructor.

Keep in mind that if you were to call handleClick1() from inside your component (as you do when improperly setting the first button handler) this will be what you expect it to be. Thats just how this works.

Here's a sandbox for anyone interested: https://codesandbox.io/s/react-playground-forked-nimby?file=/index.js

Spankied
  • 1,626
  • 13
  • 21