首页 > 解决方案 > Why are Arrow Functions in ReactJS considered as property?

问题描述

So, I've tried two different approaches as per need, i.e with Arrow Functions and Non-Arrow Functions, and while writing the code I noticed something odd about both of these, the non-arrow function i.e.

  close() {
    this.setState({
      show: false
    });
  }

are considered as method(s) which is true as they are functions, nonArrow

But when I write an Arrow function such as:

  goToNextPage = () => {
    this.setState(({ page }) => ({ page: page + 1 }));
  };

property

It is considered a property, I quite do not understand this behavior. Is this something wrong with VSCode or it is an entirely different thing?

标签: reactjsfunctionmethodsvisual-studio-codearrow-functions

解决方案


class MyClass { aClassProperty = <whatever_value>; }意味着您正在为类的每个新实例创建一个新的类属性。该属性可以是您喜欢的任何值,但在这种情况下,该属性是一个箭头函数,所以它是正确的。

aMethod()在类的每个实例之间共享,但是在 React 中,您通常通过将其绑定到构造函数来创建一个新函数this,因此最终结果是相同的。


推荐阅读