could someone explain to me why i need to use binding this.handleClick = this.handleClick.bind(this);
when using event?
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);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
And why the value of 'this' is defined?
class Person {
constructor(name, yearOfBirth) {
this.name = name;
this.yearOfBirth = yearOfBirth;
}
calculateAge() {
console.log(this);
}
}
const john = new Person('John', 1993);
john.calculateAge();
But the value of 'this' is undefined when clicked?
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
console.log(this);
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
ReactDOM.render(
<ActionLink />,
document.getElementById('root')
);