当用户点击一个按钮(实际上是一个图像)时,我会显示某个 div
<img src={notification} className="search_bar_icons" onClick={this.props.open_notifications}/>
当用户单击此图像时,我将要显示的 div 的状态更改为“true”
open_notification() {
this.setState({
showNotification: true,
});
}
这工作正常。但如果用户再次单击图像,我想将状态设置为“假”。我该怎么做?
最佳答案
您可以使用
切换您的值this.setState({ showNotification: !this.state.showNotification });
更新。目前,在 setState 中使用先前状态的更好方法是:
this.setState(prevState => ({ showNotification: !prevState.showNotification }));
关于javascript - 在 React 中通过单击切换状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42529188/