[英]How to track active link in next.js?
我的管理面板中有一个侧边栏组件,它有多个链接。 其中一些链接位于下拉菜单中。 现在我想添加一个基于活动链接的活动类,或者如果活动链接在下拉菜单中,则添加到下拉切换。 下面是我的侧边栏代码。 顺便说一句,我正在为 ui 使用 antd 框架。
<Sider
width={260}
className={styles.sider}
collapsible
trigger={null}
collapsed={drawer}
breakpoint={"md"}
collapsedWidth={0}
>
<Menu mode="inline">
<Menu.Item
icon={<IoGrid />}
key="1"
onClick={(e) => {
toggleKey(e);
gotoPage("/");
}}
className={selectedKey == 1 ? styles.active_item : ""}
>
Dashboard
</Menu.Item>
<SubMenu
title="Settings"
key="2"
icon={<IoSettingsOutline />}
className={selectedKey == 2 ? styles.active_item : ""}
>
<Menu.Item
icon={<IoPersonAddOutline />}
key="2.1"
onClick={(e) => {
toggleKey(e);
gotoPage("/settings/profile");
}}
>
Profile
</Menu.Item>
</SubMenu>
</Menu>
</Sider>
顺便说一句, selectedKey 和 toggleKey 功能来自顶级组件,而 gotoPage 只是 router.push 功能。
谢谢。
根据这个答案,您应该使用useRouter
hook 来获取当前路径。
对于您的用例而不是等式检查,您可能应该使用startsWith
或其他一些检查。 所以它看起来像这样
假设你有
Settings -> /settings
Profile -> /settings/profile
Notifications /settings/notifications
您检查当前路径是否以/settings
开头,并假设 Settings 组处于活动状态,您只需展开 Settings 子菜单并将活动类添加到 Settings 组。
如果您当前在/settings/notification
这意味着您可以识别以下内容:
我认为最好使用自定义LinkGroup
组件来检查其“活动性”并添加特定样式并显示/隐藏其子菜单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.