【问题标题】:How to track active link in next.js?如何跟踪 next.js 中的活动链接?
【发布时间】:2021-12-16 02:37:59
【问题描述】:

我的管理面板中有一个侧边栏组件,它有多个链接。其中一些链接位于下拉菜单中。现在我想添加一个基于活动链接的活动类,或者如果活动链接在下拉菜单中,然后到下拉切换。下面是我的侧边栏代码。顺便说一句,我正在为 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 功能。
谢谢。

【问题讨论】:

  • 目前的实现有什么问题?
  • 实际上当前代码的问题是在页面更改后selectedKey被重置
  • @MarioNikolaus 实际上,这些解决方案只有在没有像简单比较 router.pathname == '/dashboard' 这样的下拉列表时才有效。但是如果有一个下拉列表可以说三个进一步的链接,那么这三个链接中的任何一个都可以启用下拉列表切换器。我想要那样的。像这个子菜单一样,它可以有多个链接,并且活动类设置在子菜单上。
  • 大家看看这个链接link检查这个链接。我想要 next.js 中的这种类型的侧边栏

标签: reactjs next.js antd


【解决方案1】:

根据这个answer,您应该使用useRouter 挂钩来获取当前路径。

对于您的用例而不是相等检查,您可能应该使用startsWith 或其他一些检查。所以它看起来像这样

假设你有

Settings -> /settings
  Profile -> /settings/profile
  Notifications /settings/notifications

您检查当前路径是否以/settings 开头,并假设设置组处于活动状态,您只需展开设置子菜单并将活动类添加到设置组。

如果您目前在/settings/notification,这意味着您可以识别以下内容:

  • 活跃组
  • 活动下拉菜单
  • 活动子链接

我认为最好有自定义的LinkGroup 组件来检查其“活动性”并添加特定样式并显示/隐藏其子菜单。

【讨论】:

    猜你喜欢
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    相关资源
    最近更新 更多