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

React侧边栏选中菜单时如何添加listItemActive类更改背景色

侧边栏菜单激活状态实现方案

实现逻辑

获取当前页面的路由路径,和每个菜单项的跳转路径做匹配,匹配成功则绑定激活样式listItemActive,否则绑定普通样式listItem。

代码修改步骤

  1. 注入路由属性:使用react-router提供的withRouter高阶组件包裹Sidebar,获取当前路由的location对象
  2. 动态绑定样式:在render方法中读取当前路径,每个菜单项做路径比对后动态指定style

完整修改后代码

import React from "react";
import { Link, withRouter } from "react-router-dom"; // 引入withRouter
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faCog,
  faThLarge,
  faBriefcaseMedical,
  faSms,
  faQrcode,
} from "@fortawesome/free-solid-svg-icons";
// 注意替换为你自己的Logo资源路径
import Logo from "your-logo-path";

class Sidebar extends React.Component {
  render() {
    // 获取当前路由路径
    const currentPath = this.props.location.pathname;

    function hideBar() {
      var sidebar = document.querySelector(".sidebar");
      sidebar.classList.remove("show");
      sidebar.classList.add("hide");
    }
    return (
      <div className="sidebar" style={styles.header}>
        {/* 修正原代码class为React规范的className */}
        <a className="close-icon" href="#" onClick={hideBar}>
          &#10006;
        </a>
        <img src={Logo} alt="站点Logo" />
        <ul style={styles.lists}>
          <Link to="/client" >
            <li
              style={currentPath === '/client' ? styles.listItemActive : styles.listItem}
            >
              <div>
                <FontAwesomeIcon
                  icon={faThLarge}
                  style={{ marginRight: "1rem" }}
                />
              </div>
              <div> Dashboard</div>
            </li>
          </Link>

          <Link to="/cdoctor" >
            <li style={currentPath === '/cdoctor' ? styles.listItemActive : styles.listItem}>
              <div>
                <FontAwesomeIcon
                  icon={faBriefcaseMedical}
                  style={{ marginRight: "1rem" }}
                />
              </div>
              <div> Doctor</div>
            </li>
          </Link>

          <li style={styles.listItem}>
            <div>
              <FontAwesomeIcon icon={faSms} style={{ marginRight: "1rem" }} />
            </div>
            <div>Messages</div>
          </li>

          <Link to="/cscan">
            <li style={currentPath === '/cscan' ? styles.listItemActive : styles.listItem}>
              <div>
                <FontAwesomeIcon
                  icon={faQrcode}
                  style={{ marginRight: "1rem" }}
                />
              </div>
              <div>Upcoming Scans</div>
            </li>
          </Link>
        </ul>
        <div
          style={{
            position: "absolute",
            bottom: "3rem",
            left: "30px",
            width: "15%",
          }}
        >
          <div style={{ marginTop: "3rem" }}>
            <button
              style={{
                color: "#fff",
                textDecoration: "none",
                background: "transparent",
                border: "none",
              }}
            >
              <FontAwesomeIcon icon={faCog} style={{ marginRight: "1rem" }} />
              Settings
            </button>
          </div>
        </div>
      </div>
    );
  }
}

// 用withRouter包裹组件,注入路由属性
export default withRouter(Sidebar);

const styles = {
  header: {
    background:
      " 0% 0% no-repeat padding-box padding-box rgba(255, 255, 255, 0.11)",
    padding: "2rem",
    width: "20%",
    margin: "0",
    color: "white",
  },
  lists: {
    marginTop: "5rem",
    color: "#fff",
    paddingLeft: "0",
    listStyle: "none",
  },
  listItem: {
    background: "transparent",
    padding: "10px 50px",
    borderRadius: "10px",
    cursor: "pointer",
    whiteSpace: "nowrap",
    textAlign: "initial",
    display: "flex",
  },
  listItemActive: {
    background: "#6a0f4b",
    padding: "10px 50px",
    borderRadius: "10px",
    cursor: "pointer",
    display: "flex",
  },
};

适配React Router v6说明

如果你的项目使用React Router v6版本,该版本移除了withRouter高阶组件,你可以自行封装一个高阶组件注入路由属性,在上述代码前添加如下代码即可:

import { useLocation } from 'react-router-dom';
function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    let location = useLocation();
    return <Component {...props} location={location} />;
  }
  return ComponentWithRouterProp;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:36:07