React 类对象方法声明之间的区别?

2024-02-09

我已经看到了在类组件中声明方法的两种方法React

Method 1

class someComp extends React.Component  {  
    handleResetShapes = (e) => {
        e.preventDefault();
        this.setState({state: 'try'});
    }

    render() {}
}

Method 2

class someComp extends React.Component  {  
    handleResetShapes(e) {
        e.preventDefault();
        this.setState({state: 'try'});
    }

    render() {}
}

在那个具体的例子中Method 1有效,而另一个则无效。但是我见过声明为的方法Method 2它工作正常,只是现在无法提供示例。

Question

有什么区别?这个 Javascript 概念叫什么?


调用方法1公共类字段语法 https://babeljs.io/docs/en/babel-plugin-proposal-class-properties,使用它我们不需要担心它的含义this在运行时,因为它是自动绑定的。例如:

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

在方法 2 中,它只是类中的一个普通方法,当您使用ES6级 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

不过,在使用这种方法的时候,你必须要小心它的含义this在 JSX 回调中。在 JavaScript 中,类方法不是bound https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind默认情况下。如果忘记绑定this.handleClick并将其传递给onClick, this不明确的当函数被实际调用时。

class LoggingButton extends React.Component {
  constructor(props) {
    super(props);

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    return <button onClick={this.handleClick}>Click me</button>;
  }
}

方法1和方法2的区别在于:this当函数被实际调用时,在函数内部。


参考:处理事件 https://reactjs.org/docs/handling-events.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 类对象方法声明之间的区别? 的相关文章

随机推荐