Could you please explain to me why we need to bind “this” in our own declared methods in React class components? I do understand that the value of “this” depends on the environment where “this” is being used. However, in the code below we have 3 methods - constructor(), changeText() and render(). Why “this” works just fine in constructor() and render() but doesn’t work in my own method - changeText() unless I bind it? I have read a lot of articles on “this” but still don’t understand why our own methods should be bound to “this”…
class App extends React.Component {
constructor() {
super();
this.state = {
text: "Change Text",
};
this.changeText = this.changeText.bind(this);
}
changeText() {
this.setState({
text: "Text Changed",
});
}
render() {
return (
<div>
<div>
<h3>{this.state.text}</h3>
<button onClick={this.changeText}>Click Me</button>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));