【问题标题】:How to highlight two Menu.Item each in separate component in ANTD with React Router {pathname}如何使用 React Router {pathname} 在 ANTD 中的单独组件中突出显示两个 Menu.Item
【发布时间】:2021-05-29 08:11:26
【问题描述】:

我正在尝试在我的应用中创建导航。 我正在使用 Antd 和 React 路由器。我创建了菜单组件,它呈现并返回一个完整的菜单。有一个属性:selectedKeys 和 defaultSelectedKeys。所以它在我的两个菜单上都可以正常工作,一个通过这样的路线导航:

/x
/y
/z <- redirect to /z/a
..

第二个是这样的:

/z/a
/z/b
/z/c

所以当我点击 /y 路由 Antd 选择的键将是 /y 路由并突出显示菜单项,当我点击 /z/b 菜单中的 /z/b 项目将突出显示,但我也想突出显示/z 的父路由菜单项。 我要渲染菜单的组件:

const menuItems = routes.map(({ name, path }) => (
    <Menu.Item key={path}>
      <Link to={path}>{name}</Link>
    </Menu.Item>
  ));
  return (
    <Menu
      theme={theme}
      mode={mode}
      {...items}
    >
      { menuItems}
    </Menu>
  );

及用法:

  • 主菜单/:
<MenuItems routes={mainRoutes}  />
  • 子菜单 /z :
<MenuItems routes={subRoutes}  />

主路由和子路由实现:

const mainRoutes= [
 {
    path: '/x',
    name: 'x',
    component: ...,
  },  {
    path: '/y',
    name: 'y',
    component: ...,
  },
  {
    path: '/z',
    name: 'z',
    component: ...,
  },
];
const subRoutes = [
  {
    path: /z/a.,
    name: 'z a',
    component: ...,
  },
  {
    path: /z/b,
    name: 'z b',
    component: ...,
  },
 
];

【问题讨论】:

  • 请分享你是如何声明mainRoutes & subRoutes的?
  • @bonnopc 添加了路线设置

标签: reactjs react-router antd


【解决方案1】:

您可以在 Ant Design 的 Menu 组件中使用 selectedKeys 属性指定您的关联路由。访问here了解更多信息。

// ...
function SideBar(){
   // ...
   const location = useLocation();

   const getAssociatedPaths = () => {
       if(mainRoutes.find(route => route.path === location.pathname)){
           return null; // matched with main route
       }
       
       const firstSlug = location?.pathname.split("/")[0];
       const matchedMainRoute = mainRoutes.find(route => route.path.slice(1) === firstSlug);

       if(matchedMainRoute) return [ matchedMainRoute.path, location.pathname ];

       return null;
   }

   return (
       <Menu
           theme={theme}
           mode={mode}
           selectedKeys={getAssociatedPaths()}
           {...items}
       >
           { menuItems}
       </Menu>
   );

}

但是,如果您在 mainRoutes 中声明您的子路由,那将是一个好方法。因此,您可以轻松识别您的父路线/路径。

【讨论】:

  • 运行良好!谢谢,我必须了解有关属性用例的更多信息:)
猜你喜欢
  • 1970-01-01
  • 2023-01-17
  • 2016-09-08
  • 2020-12-24
  • 2020-10-02
  • 1970-01-01
  • 2020-05-16
  • 2020-01-13
  • 1970-01-01
相关资源
最近更新 更多