Ant Design 的 Menu 菜单为什么点击后不自动高亮选中项?

W″晓红 阅读 2

我在用 Ant Design 的 Menu 组件做侧边栏导航,但点击菜单项后,页面路由变了,菜单却不会自动高亮当前选中的那一项。我明明传了 selectedKeys 啊,是不是哪里写错了?

我试过把 location.pathname 作为 selectedKeys 传进去,但没效果。控制台也没报错,就是不亮。

const App = () => {
  const location = useLocation();
  return (
    <Menu
      mode="inline"
      selectedKeys={[location.pathname]}
      items={[
        { key: '/home', label: '首页' },
        { key: '/users', label: '用户管理' }
      ]}
    />
  );
};
我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
Des.柯佳
这个问题的核心是 key 值匹配不上。

你的代码逻辑是对的,但最可能的原因是 路由路径和 Menu item 的 key 不完全一致。比如你的路由可能是 /home/(带尾斜杠)或者 /home?id=1(带查询参数),而你的 key 是 /home

解决方法很简单,用 defaultSelectedKeys 试试:

const App = () => {
const location = useLocation();
return (
<Menu
mode="inline"
defaultSelectedKeys={[location.pathname]}
items={[
{ key: '/home', label: '首页' },
{ key: '/users', label: '用户管理' }
]}
/>
);
};


defaultSelectedKeys 是非受控模式,内部会自己维护选中状态,不用你手动同步。

如果你必须用受控模式(selectedKeys),那就打印一下 location.pathname 看看实际值是什么,可能多了斜杠或者少了个字符。

还有一种情况:如果你的 Menu 组件在 Antd Layout 里面,记得把 Menu 放在 Sider 内部,Layout 不直接管 Menu 的选中状态。
点赞
2026-03-13 09:17