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

如何使用MUI styled()为NavLink元素的激活链接添加样式?

如何用MUI的styled()给封装的NavLink添加激活状态样式?

我封装了一个NavLink组件,想在它处于激活状态时添加.active样式,但不知道怎么用styled()实现,当前代码如下:

import { forwardRef } from "react";
import { NavLink as NavLinkBase } from "react-router-dom";
import { styled } from "@mui/system";


const NavLink = forwardRef((props, ref) => {
  return (
    <NavLinkBase   
      ref={ref}
      {...props}
      className={({ isActive }) => [
        props.className,
        isActive ? 'active' : null,
      ]
        .filter(Boolean)
        .join(" ")
      }
      end={props.to === '/' ? true : false}
    />
  )
});

export default NavLink

解决方案

核心思路是利用styled()的CSS嵌套语法,通过&.active选择器匹配激活状态的元素,结合NavLink的激活类名机制实现需求。下面提供两种可行方式:

方式一:直接用styled()封装带激活样式的NavLink

这种方式无需手动拼接className,直接让styled()接管所有样式定义:

import { forwardRef } from "react";
import { NavLink as NavLinkBase } from "react-router-dom";
import { styled } from "@mui/system";

// 创建样式化的NavLink,定义基础样式和激活状态样式
const StyledNavLink = styled(NavLinkBase)(({ theme }) => ({
  textDecoration: "none",
  color: "#333",
  padding: "8px 16px",
  // 匹配激活状态的.active类
  "&.active": {
    color: theme.palette.primary.main,
    fontWeight: "bold",
    borderBottom: `2px solid ${theme.palette.primary.main}`
  }
}));

const NavLink = forwardRef((props, ref) => {
  return (
    <StyledNavLink   
      ref={ref}
      {...props}
      end={props.to === "/" ? true : false}
    />
  );
});

export default NavLink;

说明:react-router-dom的NavLink在路由匹配激活时,会自动给元素添加active类名,因此直接用&.active就能精准匹配激活状态,无需手动处理className拼接。

方式二:保留原有className逻辑,用styled()管理样式

如果需要保留你原来手动判断isActive添加类名的逻辑,可以把样式定义移到styled()中:

import { forwardRef } from "react";
import { NavLink as NavLinkBase } from "react-router-dom";
import { styled } from "@mui/system";

const StyledNavLink = styled(NavLinkBase)(({ theme }) => ({
  textDecoration: "none",
  color: "#333",
  padding: "8px 16px",
  // 激活状态样式
  "&.active": {
    color: theme.palette.primary.main,
    fontWeight: "bold"
  }
}));

const NavLink = forwardRef((props, ref) => {
  return (
    <StyledNavLink   
      ref={ref}
      {...props}
      className={({ isActive }) => [
        props.className,
        isActive ? "active" : null,
      ].filter(Boolean).join(" ")}
      end={props.to === "/" ? true : false}
    />
  );
});

export default NavLink;

说明:这种方式和你原有逻辑完全兼容,只是把.active的样式从外部CSS移到了styled()中定义,依然通过手动判断isActive添加类名,styled会自动识别并应用样式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:20:37