gpt4 book ai didi

Targeting one item in an Array ( React, useState)(以数组中的一项为目标(Reaction,useState))

转载 作者:bug小助手 更新时间:2023-10-28 13:14:47 27 4
gpt4 key购买 nike



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'}
/>

更多回答

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