Rohisha Ramauthar
Rohisha Ramauthar

Reputation: 43

React Questions

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 the 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 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

Upvotes: 1

Views: 71

Answers (1)

Spankied
Spankied

Reputation: 1895

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

Upvotes: 1

Related Questions