我在 ES6 React 代码中经常看到这种情况
class Foo extends React.Component {
bar = () => {
console.log("bar")
}
baz() {
console.log("baz")
}
}
似乎它们都在 Foo
上定义了方法 bar
和 baz
,但它们有何不同。
最佳答案
这些声明的不同之处在于函数的编写方式以及 this
的上下文
,
在第一个语法中
bar = () => {
console.log("bar")
}
该函数是使用 Arrow function
编写的句法。
An arrow function does not have its own
this
; thethis
value of the enclosing executioncontext
is used. Hencethis
keyword inside this function will refer to the context of theReact class
但是第二个声明
baz() {
console.log("baz")
}
是一个简单的函数,该函数中的this关键字
指的是函数本身的上下文。
因此,当您尝试访问 React 类属性/函数(例如 this.state
或 this.setState
)时,在第二种情况下您将收到错误(如果您没有这样做) t 在该函数的其他任何地方使用了绑定(bind)(示例构造函数)),而它在第一种情况下可以工作,因为对于箭头函数,this
在函数体内的含义与在函数体外的含义相同。这意味着,如果您在组件的自定义函数中使用箭头函数,它们可以毫无意外地使用 this
和 this.setState
。
关于javascript - ES6中React类定义方法的两种方式有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47587470/