【发布时间】:2021-12-13 05:37:18
【问题描述】:
我在我的 react 应用程序中将 react-sidebar-pro 用于我的侧边栏组件,我希望当用户单击并重定向到链接时,我的侧边栏菜单项的活动状态变为 true。到目前为止,我所做的是设置一个参数,如果用户位于特定地址,它将变为 true,但它仅在我刷新页面时更新。如何在不刷新页面的情况下更新它,使其看起来响应?我想过使用 useState 来解决这个问题,但我不知道如何将它应用到代码中,因为我还在学习 React
这是我的 Sidebar.js
function Sidebar() {
//create initial menuCollapse state using useState hook
const [menuCollapse, setMenuCollapse] = useState(false)
//create a custom function that will change menucollapse state from false to true and true to false
const menuIconClick = () => {
//condition checking to change state from true to false and vice versa
menuCollapse ? setMenuCollapse(false) : setMenuCollapse(true);
}
return (
<>
<div id="header">
{/* collapsed props to change menu size using menucollapse state */}
<ProSidebar collapsed={menuCollapse}>
<SidebarHeader>
<div className="logotext">
{/* small and big change using menucollapse state */}
<p>{menuCollapse ? "LOGO" : "LONG LOGO"}</p>
</div>
<div className="closemenu" onClick={menuIconClick}>
{/* changing menu collapse icon on click */}
{menuCollapse ? (
<FiArrowRightCircle/>
) : (
<FiArrowLeftCircle/>
)}
</div>
</SidebarHeader>
<SidebarContent>
<Menu iconShape="square">
<MenuItem active={window.location.pathname === "/"} icon={<FiHome />} >
Home
<Link to="/"/>
</MenuItem>
<MenuItem active={window.location.pathname === "/FAQ"} icon={<FaList />}>
FAQ
<Link to="/FAQ"/>
</MenuItem>
<MenuItem active={window.location.pathname === "/Search-sec"} icon={<RiPencilLine />}>SEARCH SEC<Link to="/Search-sec"/></MenuItem>
</SidebarContent>
<SidebarFooter>
<Menu iconShape="square">
<MenuItem icon={<FiLogOut />}>Logout</MenuItem>
</Menu>
</SidebarFooter>
</ProSidebar>
</div>
</>
)
}
export default Sidebar
【问题讨论】:
-
因为 react 组件不知道
window.location更改,因为window.location不是 prop 或本地状态。因此,组件不会重新渲染。
标签: javascript reactjs react-native react-hooks react-router