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>
);
}
}
thisworks: github.com/getify/You-Dont-Know-JS/blob/… . Then it should be clear.