Have the following simpliest component.
class App extends Component {
constructor(props) {
super(props);
console.log(this);
this.state = {
name: "John"
}
}
clickHandler() {
this.setState({
name: "Mark"
})
};
render() {
return (
<div className="App">
{this.state.name}
<button onClick={this.clickHandler.bind(this)}></button>
</div>
)
};
}
export default App;
If I write that
<button onClick={this.clickHandler}></button>
it says that this in
this.setState({
name: "Mark"
})
is undefined. That row
<button onClick={console.log(this)}></button>
shows that this is App. So if this is App why clickHandler does not bind automatically to that object before the dot?
<button onClick={this.clickHandler}></button>
As far as I understand in "context.function" the context should be bound to the function. Or it only works for "context.function()"?
Or it only works for "context.function()"?
That's exactly right. It depends on where the function is invoked.
Doing
<button onClick={this.clickHandler}></button>
passes the clickHandler as a parameter. React's internals see something not completely dissimilar to:
function button({ onClick }) {
// ...
theActualDOMButtonElement.addEventListener('click', onClick);
}
or
function button({ onClick }) {
// ...
theActualDOMButtonElement.addEventListener('click', (e) => {
const reactCreatedSyntheticEvent = retrieveSyntheticEvent(e);
onClick(reactCreatedSyntheticEvent);
});
}
You're passing the this.clickHandler as a parameter, not invoking it immediately - since it gets invoked later, and how it's invoked later determines the this, you can't just do onClick={this.clickHandler} without making sure the this is correct, such as invoking the function inline, or by using a class field, or by using a functional component.