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

ReactJS:使用React Pro Sidebar时无法为菜单项设置Active激活类

React Pro Sidebar 的 <MenuItem> 组件原生支持 active 布尔属性,你只需要将当前页面路由和菜单项对应的路由做匹配,给命中的菜单项的 active 属性赋值为 true 即可。

如果你用的是 react-router 作为路由方案,实现逻辑如下:

完整代码示例

import { useLocation } from 'react-router-dom';
import { SidebarContent, Menu, MenuItem } from 'react-pro-sidebar';
import { IoHomeOutline, IoPeopleOutline, IoCellularOutline } from 'react-icons/io5';
import { Link } from 'react-router-dom';

const Sidebar = () => {
  // 获取当前页面路由
  const { pathname } = useLocation();

  return (
    <SidebarContent>
      <Menu iconShape="square">
        <MenuItem 
          icon={<IoHomeOutline />}
          active={pathname === '/home'}
        >
          Home
          <Link to="/home" />
        </MenuItem>

        <MenuItem 
          icon={<IoPeopleOutline />}
          active={pathname === '/oncalls'}
        >
          HighSev OnCalls
          <Link to="/oncalls" />
        </MenuItem>

        <MenuItem 
          icon={<IoCellularOutline />}
          active={pathname === '/reports'}
        >
          Reports
          <Link to="/reports" />
        </MenuItem>
      </Menu>
    </SidebarContent>
  );
};

export default Sidebar;

样式自定义说明

组件默认会给active为true的菜单项添加高亮样式,如果你需要自定义激活样式,可以直接覆盖组件默认类名:

/* 示例:自定义激活态背景和文字颜色 */
.ps-menu-button.ps-active {
  background-color: #e6f7ff;
  color: #1890ff;
}

如果你有嵌套路由场景(比如/reports/detail、/reports/list都要激活Reports菜单项),可以把判断逻辑改成 active={pathname.startsWith('/reports')} 即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:54:04