deB*_*lis 0 javascript reactjs arrow-functions
我当时在React.js应用程序上工作,最初使用的是箭头功能,但出于好奇,我决定尝试正常功能,但正常功能无效。我认为他们都应该输出相同的内容,这是怎么回事?
handleChange = event => this.setState({init: event.target.value})
handleChange(event){
this.setState({init: event.target.value})
}
Run Code Online (Sandbox Code Playgroud)
箭头功能和法线功能不相等。
区别在于:
箭头函数没有自己的绑定功能this,因此请this.setState参考YourClass.setState。
使用常规功能,您需要将其绑定到类以获得Class的this引用。因此,当您this.setState实际调用它时,它指的是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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1361 次 |
| 最近记录: |