G
G
glebvvs2018-08-31 02:18:15
React
glebvvs, 2018-08-31 02:18:15

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

What is the magic of these arrow functions? Or is it some kind of JSX feature that I don't understand?
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

1 answer(s)
A
Anton Spirin, 2018-08-31
@glebvvs

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>
    );
  }

}

Arrow functions have no context and use the context of the environment where they are defined.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question