版权声明:转载请注明作者(独孤尚良dugushangliang)出处: https://blog.youkuaiyun.com/dugushangliang/article/details/90581414
我的另一个文章https://blog.youkuaiyun.com/dugushangliang/article/details/90580582中的代码如下:
//handleClick使用bind绑定函数
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 这边绑定是必要的,这样 `this` 才能在回调函数中使用
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('example')
);
对于handleClick中的prevState很不解。因为button并没有传值给handleClick。
经多次试验,把handleClick改成如下代码:
handleClick() {
this.setState(prevState => {
console.log(prevState);
return ({
isToggleOn: !prevState.isToggleOn
})});
}
控制台信息如下:
感谢https://www.cnblogs.com/libin-1/p/6725774.html给我的灵感:
是的,通过控制台,我们验证了这个说法——prevState是React的前一个State(状态) 。
但在handleClick中,使用prevState和this.prevState都执行失败,但在this.setState()可以正常运行。所以个人猜测这个属性应该是只能用于this.setState()中。
独孤尚良dugushangliang——著