本文介绍了类对象方法声明之间的区别React?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了在React

方法1

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

    render() {}
}

方法2

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

    render() {}
}

在该特定示例中,Method 1有效,而另一个无效.但是,我已经看到方法声明为Method 2,并且效果很好,只是现在无法提供示例.

In that specific example Method 1 worked and the other didn't. However I have seen methods declared as Method 2 and it works fine, just can't provide an example now.

问题

有什么区别,Javascript概念叫什么?

What is the difference and what is that Javascript concept called?

推荐答案

方法1称为公共类字段语法,使用它,我们不必担心this在运行时的含义,因为它是自动绑定的.例如:

Method 1 is called public class fields syntax, using it and we don't need to worry about the meaning of this in runtime because it's automatically bound. For example:

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类

但是,使用此方法时,必须注意JSX回调中this的含义.在JavaScript中,类方法不受绑定默认情况下.如果您忘记绑定this.handleClick并将其传递给onClick,则在实际调用该函数时this将为 undefined (未定义).

However, when using this method, you have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

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的含义.


The difference between method 1 and method 2 is about the meaning of this inside the function when the function is actually called.

参考:处理事件

这篇关于类对象方法声明之间的区别React?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 19:50
查看更多