I am new to react. I created an array of items with each switch element, the problem is: when I click on one item all items are activated at once!
我对此的反应是新的。我用每个开关元素创建了一个项目数组,问题是:当我单击一个项目时,所有项目都会同时激活!
const dashboardItems = ["news", "notifications", "letters"];
const Settings = (props) => {
const { t } = useTranslation("settings");
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(!isActive);
};
return (
<SideMenu class="dashboard-settings">
<SideMenu.Item>
<SideMenu.Header>{t("Dashboard Settings")}</SideMenu.Header>
</SideMenu.Item>
{dashboardItems.map((dashboardItem) => (
<SideMenu.Item key={dashboardItem}>
{t(dashboardItem)}{" "}
<Switch
onClick={handleClick}
status={isActive ? "active" : "inactive"}
/>
</SideMenu.Item>
))}
</SideMenu>
);
};
I tried many solutions I found through search but they did not work.
我尝试了许多通过搜索找到的解决方案,但都不起作用。
更多回答
优秀答案推荐
You're using a single value for all items. Instead convert the isActive
state to an object (like the example), or array (use indexes instead of item), and toggle the item on the object.
您正在为所有项使用单个值。相反,将isActive状态转换为对象(如本例)或数组(使用索引而不是项),并切换对象上的项。
The state:
州政府:
const [isActive, setIsActive] = useState({});
The switch:
开关:
<Switch
onClick={() => {
setIsActive(s => ({
...s,
[dashboardItem]: !s[dashboardItem]
}))
}
status={isActive[dashboardItem] ? 'active' : 'inactive'}
/>
更多回答
我是一名优秀的程序员,十分优秀!