[英]React: if 1 state is true, change others to false
I have 4 buttons, for each of which I applied the following functions:我有 4 个按钮,我为每个按钮应用了以下功能:
handleStip() {
this.setState({isStipOpen: !this.state.isStipOpen, isBookmarkOpen: false, isDonateOpen: false});
}
handleBookmark() {
this.setState({isBookmarkOpen: !this.state.isBookmarkOpen, isStipOpen: false, isDonateOpen: false});
}
handleDonate(){
this.setState({isDonateOpen: !this.state.isDonateOpen, isStipOpen: false, isBookmarkOpen: false});
}
I have no problems with the functionality.我的功能没有问题。 The main problem is size.
主要问题是尺寸。 For example, now I need to add 2 more buttons, again copying and pasting all these states.
例如,现在我需要再添加 2 个按钮,再次复制和粘贴所有这些状态。
Is there a more elegant way to solve this problem?有没有更优雅的方法来解决这个问题? Thanks
谢谢
How about creating a generic function that can receive the key that you want to toggle.如何创建一个可以接收您想要切换的键的通用 function。 Create a state copy.
创建 state 副本。 Iterate all keys and set them to false.
迭代所有键并将它们设置为 false。 Set the key in question to toggle state.
将相关键设置为切换 state。
handleButtonStateChange = (toggleKey) => {
const stateCopy = {...this.state};
const nextValue = !stateCopy[toggleKey];
Object.keys(stateCopy).forEach(key => stateCopy[key] = false);
stateCopy[toggleKey] = nextValue;
this.setState(stateCopy);
}
Usage用法
onChange={() => this.handleButtonStateChange('isBookmarkOpen')}
Maybe you can create function what will create object with false values也许你可以创建 function 什么会创建 object 假值
const prepareData = () => ({
isStipOpen: false
isBookmarkOpen: false,
isDonateOpen: false
});
handleEvent(type) {
this.setState({...this.prepareData(), [type]: !this.state[type]});
}
But i do not know you logic, maybe it will not work但我不知道你的逻辑,也许它不会工作
According to comment above we can use type
param根据上面的评论,我们可以使用
type
参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.