Answer the question
In order to leave comments, you need to log in
Why do React events only work through arrow functions?
I can't understand a probably simple thing. Why is it that when I assign an arrow function to the changeStylesForCaption property, the onClick event of the H1 header fires.
But if I use an anonymous function instead of an arrow function, or I make the changeStylesForCaption property a class method, then the following error occurs:
Cannot read property 'setState' of undefined
import React, { Component } from 'react';
class MainPage extends Component {
changeStylesForCaption = () => {
this.setState({
color: 'black'
});
}
constructor(props) {
super(props);
this.state = {
color: 'red'
};
}
render() {
return (
<h1 onClick={this.changeStylesForCaption} style={{ color: this.state.color }}>gleb</h1>
);
}
}
export default MainPage;
Answer the question
In order to leave comments, you need to log in
Because when you call a method on an object:
or:
The object reference given before the dot will be used as the context and will be available in the function, via the this keyword.
When you pass a method without calling:
or:
Only the method is passed and the context is lost.
In order not to lose context when passing a method to a listener, you can use the bind function . On your example:
class MainPage extends Component {
constructor(props) {
super(props);
this.state = {
color: 'red'
};
this.changeStylesForCaption = this.changeStylesForCaption.bind(this); // привязываем контекст
}
changeStylesForCaption() {
this.setState({
color: 'black'
});
}
render() {
return (
<h1 onClick={this.changeStylesForCaption} style={{ color: this.state.color }}>gleb</h1>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question