gpt4 book ai didi

javascript - react : Handling Events - parameter visibility

转载 作者:行者123 更新时间:2023-11-28 14:09:40 25 4
gpt4 key购买 nike

我正在关注 React 文档。在'Handling Events ' 部分,下面的代码段就在那里。

class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}

render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}

ReactDOM.render(
<Toggle />,
document.getElementById('root')
);

handleClick()函数中,如何访问state?为什么不this.state

最佳答案

这就是 this.setState 的工作原理,它是为 this.setState() 传递的更新程序回调,根据 react documentation :

Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting

更多信息可参见here也是如此。

关于javascript - react : Handling Events - parameter visibility,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60019535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com