React+Ant Design项目Navbar导航栏选中后无法取消选中问题求助
问题根源
- 所有菜单项分别包裹在独立的
<Menu>组件中,每个Menu组件维护独立的选中状态,点击不同菜单项时无法联动取消其他项的选中状态 - 未给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
相关产品推荐
相关产品推荐

