I'm learning React and trying to understand the difficulty of "this". I know that "this" in method will refer to "button" instead of instance of the class without binding "this". So I plan to verify this conclusion, but when I click the button, the browser console displays “undefined” instead of button element. I'm quite confused.
I know that I should bind "this" manually and shouldn't use class components. I just want to test it and during my learning process, I encountered a problem that I don't know the reason.
import React from "react";
export class HerCom extends React.Component {
constructor(props) {
super(props);
this.state = { happy: 100 };
}
handleClick() {
const newHappy = this.state.happy === 100 ? 0 : 100;
this.setState({ happy: newHappy });
}
testThis() {
console.log(this);
}
render() {
return (
<div>
<button onClick={this.testThis}>Click</button>
</div>
);
}
}
I hope someone can tell me why I didn't get the expected result.