如何保持React中选择的活动菜单



我在组件中有一些菜单项,并为所选菜单项添加了一些样式。刷新页面时,我希望所选菜单保持不变,而不是初始状态。


import ClaimData from "./Data";

const Services = () => {
const [tabIndex, setTabIndex] = useState(1);
const [selected, setSelected] = useState(1);

return (
<section >
<h3>
Menu
</h3>
<div>
{ClaimData.map((item, index) => {
return (
<div
key={index}
style={
selected === item.tabNum
? {
borderBottom: "3px solid green",
backgroundColor: "#E8E8E8",
}
: null
}
onClick={() => setSelected(item.tabNum)}
>
<p
onClick={() => setTabIndex(item.tabNum)}
style={{ color: item.color }}

>
<item.icon />
<span>{item.title}</span>
</p>
</div>
);
})}
</div>

<div>
{tabIndex === 1 && <MenuOneComponent />}
{tabIndex === 2 && <MenuTwoComponent />}
{tabIndex === 3 && <MenuThreeComponent />}

</div>
</section>
);
};
export default Services;

为了简洁起见,我删除了一些代码。我将感谢的任何帮助

要在刷新时预先列出状态,需要将状态存储在react之外。最简单的可能是使用localStorage或sessionStorage。但是,当然可以将其保存在数据库/redis中。

一种方法是使用url来确定要突出显示的菜单。

最新更新