Home > Back-end >  Why does arrow function work but regular function does not React JS
Why does arrow function work but regular function does not React JS

Time:01-10

here is my code:

import React from 'react';

export default class MovieCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = { content: 'test' };
  }

  changer = () => {
    this.setState({ content: 'changed' });
  };

  //   changer() {
  //     this.setState({ content: 'changed' });
  //   }
  render() {
    return (
      <div>
        <h1>{this.state.content}</h1>
        <button onClick={this.changer}>click me to change</button>
      </div>
    );
  }
}

The regular function (I commented it out) should do the same but it does not work, while the arrow function work and change the state of the h1 element.

why is that? what is the problem?

CodePudding user response:

Because 'this' value in arrow function is the same 'this' value of its parent scope. 'this' value in regular function in class is defined in run time and it's gonna be the instance which called the Class.

CodePudding user response:

You need to bind this if you are going to use them. Arrow functions do not need binding because arrow function does not have the following in its context:

  • this

  • arguments

  • super

  • new.target

    constructor(props) {
      super(props);
      this.state = { content: "test" };
      this.changer = this.changer.bind(this);
    }
    
    changer() {
      this.setState({ content: "changed" });
    }
    render() {
      return (
        <div>
          <h1>{this.state.content}</h1>
          <button onClick={this.changer}>click me to change</button>
        </div>
      );
    }
    

CodePudding user response:

You need to bind this in order to work.

import React from 'react';

export default class MovieCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = { content: 'test' };
  }

  changer() {
    this.setState({ content: 'changed' });
  }
  render() {
    return (
      <div>
        <h1>{this.state.content}</h1>
        <button onClick={this.changer.bind(this)}>click me to change</button>
      </div>
    );
  }
}
  •  Tags:  
  • Related