Yan*_*Tay 5 javascript this reactjs
我期待看到undefined“没有约束力”被点击按钮时,因为当你明明白白传递方法引用作为回调,不应该用正确的所谓被记录this下,但有一个箭头的功能,它应该。
但是,我看到回调函数可以访问this并且this.state.number正确记录了 的值。方法引用和箭头函数执行完全相同。为什么?
这与箭头函数类属性无关,它与传递对方法的引用作为回调而setState不是箭头函数有关。
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 1,
};
}
onClickWithThisBindingInCallback = () => {
this.setState({ number: 2 }, () => { this.myCallback(); });
};
onClickWithoutThisBindingInCallback = () => {
const myCb = this.myCallback;
this.setState({ number: 3 }, myCb);
};
myCallback() {
console.log(this.state.number);
}
render() {
return (
<div className="App">
<button onClick={this.onClickWithThisBindingInCallback}>With binding</button>
<button onClick={this.onClickWithoutThisBindingInCallback}>Without binding</button>
</div>
);
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/react@16.2.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.2.0/umd/react-dom.development.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1818 次 |
| 最近记录: |