Learning about handling events in React, can someone else how the binding works in both scenarios below? If you can reference the handleClick with this.handleClick, why do you still need to bind it? Wouldn't this inside the handler already be pointing to the component because it's the component who calls the handler? Also, why does placing the handler in an annonymous function also work?
You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
The solution is this:
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
But why does this also work?
class LoggingButton extends React.Component {
handleClick() {
console.log('this is:', this);
}
render() {
// This syntax ensures `this` is bound within handleClick
return (
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
);
}
}
Because arrow functions (it is this in your case: (e) => this.handleClick(e)) will automatically "bind" this for you even if you don't call bind(this) on function. So here:
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>
The anonymous function is given the correct enclosing context (The LoginButton component in your case) automatically and it has handleClick method. And that's way it works.
And this way you can also make this this.handleClick = this.handleClick.bind(this); into an arrow function like this this.handleClick = () => this.handleClick; and get the same result.
Look here for detailed explanation:
An arrow function does not create its own this context, so this has the original meaning from the enclosing context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With