React.js和Arrow函数与普通函数 [英] React.js and arrow functions vs normal functions
问题描述
我当时正在使用react.js应用程序,最初使用的是箭头功能,但出于好奇,我决定尝试使用正常功能,但正常功能无效.我认为他们俩都应该输出相同的内容,这是怎么回事?
I was working on a react.js app and I initially used the arrow function which worked, but then just out of curiosity I decided to try the normal function and the normal function didn't work. I think that they both should output the same thing, what is going wrong?
handleChange = event => this.setState({init: event.target.value})
handleChange(event){
this.setState({init: event.target.value})
}
推荐答案
箭头功能和普通功能不相同.
Arrow functions and normal function are not equivalent.
这是区别:
-
箭头功能没有具有其自己的
this
绑定,因此您的this.setState
引用了YourClass.setState
.
Arrow function do not have their own binding of
this
, so yourthis.setState
refer to theYourClass.setState
.
使用常规功能,您需要将其绑定到类以获得Class的this
引用.因此,当您呼叫this.setState
时,它实际上是指YourFunction.setState()
.
Using normal function, you need to bind it to the class to obtain Class's this
reference. So when you call this.setState
actually it refer to YourFunction.setState()
.
示例代码
class FancyComponent extends Component {
handleChange(event) {
this.setState({ event }) // `this` is instance of handleChange
}
handleChange = (event) => {
this.setState({ event }) // `this` is instance of FancyComponent
}
}
这篇关于React.js和Arrow函数与普通函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!