为什么箭头函数可以工作但常规函数不能 React JS

Why does arrow function work but regular function does not React JS

这是我的代码:

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

常规函数(我把它注释掉了)应该做同样的事情但它不起作用,而箭头函数起作用并改变 h1 元素的状态。

这是为什么?有什么问题?

因为箭头函数中的 'this' 值与其父作用域的 'this' 值相同。 'this' class 中常规函数中的值是在 运行 时间内定义的,它将成为调用 Class.

的实例

您需要绑定 this 才能工作。

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

如果要使用它们,您需要绑定 this。箭头函数不需要绑定,因为箭头函数在其上下文中没有以下内容:

  • 这个

  • 参数

  • 超级

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