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

如何根据状态自定义MUI按钮的禁用样式

解决MUI按钮禁用状态样式自定义问题

MUI的contained类型按钮在禁用状态下,默认会覆盖自定义背景色,你可以通过在sx属性中针对.Mui-disabled类设置样式来解决这个问题,无需修改全局主题。

修改Button组件的sx配置,添加禁用状态的专属样式规则:

<Button
  variant="contained"
  sx={{
    fontWeight: 600,
    backgroundColor: isContributor ? "#DCB45B" : "#dc071b",
    // 定位禁用状态并自定义样式
    "&.Mui-disabled": {
      backgroundColor: "#dc071b", // 设置你需要的禁用态背景色
      opacity: 0.6, // 可选:调整透明度增强禁用视觉提示
      color: "#fff" // 可选:自定义禁用态文字颜色
    }
  }}
  startIcon={<Add />}
  onClick={handleCreateClick}
  disabled={!isContributor}
>
  Add Request
</Button>

核心说明

  • &.Mui-disabled是MUI内置的禁用状态选择器,优先级高于默认样式,能确保自定义样式生效
  • 可根据需求调整backgroundColor、opacity、color等属性,匹配你的设计风格

修改后的完整组件代码:

"use client";

import { useContext } from "react";
import Link from "next/link";
import Image from "next/image"; // 补充原代码遗漏的Image导入
import s from "./HeaderNav.module.scss";
import { usePathname } from "next/navigation";
import { useRouter } from "next/navigation";
import { Button } from "@mui/material";
import { Add } from "@mui/icons-material";
import { AuthContext } from "@/utils/contexts/AuthContext";

type Route = {
  path: string;
  label: string;
};

export default function HeaderNavigation() {
  const { isContributor } = useContext(AuthContext);
  const pathname = usePathname();
  const router = useRouter();
  const { push } = router;
  const handleCreateClick = () => {
    push("/requirements/create");
  };
  let routes: Route[];

  switch (pathname) {
    case "/special-page":
      routes = [
        // ...navigation items specific to '/special-page'
      ];
      break;

    default:
      routes = [
        { path: "/", label: "Home" },
        { path: "/requirements", label: "Requests" },
        // ...default navigation items
      ];
      break;
  }

  return (
    <nav className={s.navigation_header}>
      <Link className={s.logo} href="/">
        <Image src={drmtlogo} alt="Logo" />
      </Link>
      <ul className={s.nav_items}>
        {routes.map((route, index) => (
          <li key={index}>
            <Link href={route.path}>{route.label}</Link>
          </li>
        ))}
      </ul>
      <Button
        variant="contained"
        sx={{
          fontWeight: 600,
          backgroundColor: isContributor ? "#DCB45B" : "#dc071b",
          "&.Mui-disabled": {
            backgroundColor: "#dc071b",
            opacity: 0.6,
            color: "#ffffff"
          }
        }}
        startIcon={<Add />}
        onClick={handleCreateClick}
        disabled={!isContributor}
      >
        Add Request
      </Button>
    </nav>
  );
}

注:原代码遗漏了Image组件的导入,已补充,避免运行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:40:23