gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:40:18 25 4
gpt4 key购买 nike

我在 ES6 React 代码中经常看到这种情况

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

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

似乎它们都在 Foo 上定义了方法 barbaz,但它们有何不同。

最佳答案

这些声明的不同之处在于函数的编写方式以及 this上下文

在第一个语法中

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

该函数是使用 Arrow function 编写的句法。

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关键字指的是函数本身的上下文。

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

why you need to bind functions in React classes 上查看此答案

关于javascript - ES6中React类定义方法的两种方式有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47587470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com