You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Ant Design项目Navbar导航栏选中后无法取消选中问题求助

问题根源

  1. 所有菜单项分别包裹在独立的 <Menu> 组件中,每个Menu组件维护独立的选中状态,点击不同菜单项时无法联动取消其他项的选中状态
  2. 未给Menu组件绑定受控选中属性,无法和当前路由联动自动更新选中状态

修复方案

直接修改 Navbar.jsx 代码即可:

import { useLocation } from 'react-router-dom';
// 其他原有导入(Avatar、Typography、各类图标等)保持不变

const Navbar = () => {
  // 获取当前路由路径
  const location = useLocation();
  // 以路由路径作为选中项的唯一标识
  const selectedKey = location.pathname;

  return (
    <div className="nav-container">
      <div className="logo-container">
        <Avatar src={icon} size="large" />
        <Typography.Title level={2} className="logo">
          <Link to="/">Krypton</Link>
        </Typography.Title>
      </div>
      {/* 所有菜单项放在同一个Menu组件内,绑定选中状态 */}
      <Menu theme="dark" selectedKeys={[selectedKey]}>
        <Menu.Item key="/" icon={<HomeOutlined />}>
          <Link to="/">Home</Link>
        </Menu.Item>
        <Menu.Item key="/cryptocurrencies" icon={<FundOutlined />}>
          <Link to="/cryptocurrencies">Cryptocurrencies</Link>
        </Menu.Item>
        <Menu.Item key="/exchanges" icon={<MoneyCollectOutlined />}>
          <Link to="/exchanges">Exchanges</Link>
        </Menu.Item>
        <Menu.Item key="/news" icon={<BulbOutlined />}>
          <Link to="/news">News</Link>
        </Menu.Item>
      </Menu>
    </div>
  );
}

以上方案适配Ant Design v4、v5所有主流版本,无需额外调整其他代码。


内容的提问来源于stack exchange,提问作者Harsh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:45:00