【发布时间】:2019-10-19 21:45:35
【问题描述】:
在React.Component 类中使用bind用户创建的方法是一种常见的做法。
class App extends React.Component { // simplified example, not actual code
constructor(){
//...
this.logIn=this.logIn.bind(this) // Binding of a method
}
}
当然,这是因为我们需要将bind 方法显式地指向“this class”,否则我们将使用this 引用window 对象!
但我不清楚什么,至少从我查看的文档等来看,如果我们使用内置的生命周期方法,例如 render() 或 componentDidMount() strong>,大部分代码 sn-ps 以及官方文档似乎没有明确地 bind 到 this
class App extends React.Component {
constructor(){
//....
this.componentDidMount = this.componentDidMount.bind(this)
// is there reason why we don't do this ^ ??
}
}
- 我们扩展的
React.Component中是否已经存在一些内置绑定? - 或者为什么我们不需要像我们创建的其他方法一样显式地
bind生命周期方法(componentDidMount()) (logIn())?
【问题讨论】:
-
你自己什么时候会打电话给
componentDidMount?绑定其他函数的原因是当您将函数作为回调传递时,如果您没有绑定它,它将变为未绑定,但如果您从未将this.componentDidMount作为回调传递,则无需担心 -
如果你想测试一下,我建议你制作一个带有按钮的组件,并将onClick设置为
this.componentDidMount,看看会发生什么。然后你会自己发现它是否绑定。<button onClick={this.componentDidMount}/> -
@TKoL 诚然,是的,我没有想到它背后的大局是我们很少会真正回调“生命周期方法”。虽然从理论上讲,它仍然是一个关于为什么或是否绑定的有效问题(正如您在评论中指出的那样,现在我自己检查一下)
-
生命周期方法来自父类,即
React.Component。因为它们已经绑定在父级中,而你只是覆盖它们,你不需要再次绑定它们 -
Afaik 这些方法是绑定的,因为 React 库不使用 ES6 类。示例代码:jsfiddle.net/khrismuc/fnjs468g
标签: javascript reactjs methods binding extension-methods