Babel 正在发挥它的魔力,这让我对发生的事情感到非常困惑。
这个react组件中的foo和bar有什么区别?我什么时候应该使用哪个?
class MyComponent extends Component {
foo() {
//...
}
bar = () => {
//...
}
}
(我自己的猜测是 foo 在原型(prototype)中,而 bar 在构造函数中?反正我不知道我在说什么)
最佳答案
My own guess is foo is in the prototype, and bar is in the constructor?
完全正确。
foo() {}
在此上下文中是一个方法声明,并且值被分配给原型(prototype)。相当于
MyComponent.prototype.foo = function() {};
bar = ... ;
另一方面是一个类字段。这是在构造函数中为实例分配属性的简写符号:
constructor() {
this.bar = ... ;
}
并且由于箭头函数的工作方式,使用带有箭头函数的类字段基本上可以让您创建“绑定(bind)”方法。
关于箭头函数的更多信息:Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?
And when should I use which?
tl;dr 是:当您需要绑定(bind) 函数时,使用类字段 + 箭头函数。
什么时候需要绑定(bind)函数?每当您希望函数内部的 this
引用特定值但您无法控制调用函数的方式时。
对于需要访问组件实例(例如调用 this.setState
或访问 this.props
/this.state
)。
尽管您必须使用它,您也可以在需要时绑定(bind)该方法。然而,在构造函数中只绑定(bind)一次方法对于 React 组件来说是理想的,这样,如果该方法作为事件处理程序传递,则始终传递相同的函数对象。
如另一个答案所述,这与 React 完全无关。类字段可能会在今年正式集成到该语言中。
关于javascript - 在 React 组件中,foo(){} 和 bar = () => {} 有什么区别,什么时候应该使用哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50070655/