ES6中React类的两种方法定义方式有什么区别

ES6中React类的两种方法定义方式有什么区别

问题描述:

我在ES6 React代码中看到了很多

I see this a lot in ES6 React code

class Foo extends React.Component {
  bar = () => {
    console.log("bar")
  }

  baz() {
    console.log("baz")
  }
}

似乎它们都在 Foo 上定义了 bar baz 的方法,但是它们有何不同.

Seems like they both define methods bar and baz on Foo but how are they different.

声明的不同之处在于函数的编写方式以及 this

The declarations differ in how the function are written and the context of this,

使用第一种语法

bar = () => {
    console.log("bar")
  }

该函数使用 Arrow函数编写 语法.

the function is written using Arrow function syntax.

箭头功能没有自己的 this ;的 this 值使用封闭的执行 context .因此,其中的 this 关键字此函数将引用 React类

An arrow function does not have its own this; the this value of the enclosing execution context is used. Hence this keyword inside this function will refer to the context of the React class

但是第二个声明

baz() {
    console.log("baz") 
}

是一个简单的函数,此函数中的 this关键字指的是函数本身的上下文.

is a simple function and this keyword in this function refers to the context of the function itself.

因此,当您尝试访问React类的属性/函数(例如 this.state this.setState )时,在第二种情况下会出现错误(如果您没有t在此函数(示例构造函数)的其他任何地方都使用了绑定,而在第一种情况下它将起作用,因为对于箭头函数, this 在函数体内与在其外部含义相同.这意味着,如果您在组件的自定义函数中使用箭头功能,它们可以毫无疑问地使用 this this.setState .

So when you try to access React class Properties/functions like this.state or this.setState you will get an error in the second case(if you haven't used binding anywhere else for this function(example constructor)) whereas it would work in the first case since for an arrow function, this means the same thing within the function body as it does outside of it. Which means that if you use arrow functions within your component’s custom functions, they can use this and this.setState with no surprises.

Check this answer on why you need to bind functions in React classes