通常的做法是在bind
类中使用 React.Component
用户创建的方法。
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()
或 {{1 }} ,大多数代码段以及官方文档似乎没有从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()
) }})?答案 0 :(得分:1)
我使用以下内容制作了一个组件:
...
componentDidMount() {
var that = this;
var x = 0;
}
...
render() {
....
<button onClick={this.componentDidMount}>DID MOUNT</button>
....
}
结果在-最初安装该函数时,that
已正确绑定,但是从按钮单击时却没有绑定。
这意味着componentDidMount尚未绑定,但它是从React内部使用适当的上下文调用的,因此它不需要绑定。
-编辑
也许还需要注意:如果使用自动绑定包,它是否绑定了生命周期方法,则值得检查。 autobind-decorator
实际上可以!
答案 1 :(得分:-2)
自然,这是因为我们需要将方法显式绑定到“此类”,否则我们将以此窗口对象进行引用!
您还可以使用箭头功能而无需绑定即可使用此功能:
sayHello=()=>{
return 'hello';
}
myOtherFunction=()=>{
console.log('I can acces the other function! Say:'+ this.sayHello())
}
您不需要绑定生命周期方法
编辑:如文档在https://reactjs.org/docs/handling-events.html
中所述您必须小心JSX回调中的含义。在JavaScript中,默认情况下不绑定类方法。如果忘记绑定this.handleClick并将其传递给onClick,则在实际调用该函数时将无法定义。
因此,默认情况下,生命周期方法是绑定的。