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

MUI CSS变量覆盖失效:自定义主题下按钮仍显示默认主色

MUI自定义主题主色不生效问题

问题说明

在React组件库中封装了可复用的ManageButton组件,尝试通过自定义MUI主题设置主色为#153d77,但按钮始终显示MUI默认主色,自定义配置未生效。

相关代码

ManageButton.tsx 组件代码

interface ManageButtonProps {
    size?: 'small' | 'medium' | 'large';
    name?: string;
    dataCy?: string;
    startIcon?: React.ReactNode;
    onClick: () => void;
    children?: React.ReactNode;
}

export function ManageButton(props: ManageButtonProps) {
    return (
        <Button
            name={props.name}
            data-cy={props.dataCy ?? 'manage-button'}
            className="pushRight"
            onClick={() => props.onClick()}
            variant="contained"
            color="primary"
            size={props.size ?? 'large'}
            startIcon={props.startIcon ?? <SettingsIcon />}>
            {props.children ? props.children : 'Manage'}
        </Button>
    );
}

组件使用方式

<ManageButton onClick={() => console.log('Button clicked')}>Library Button</ManageButton>

全局CSS变量配置

:root {
  --primary-color: #153d77;
}

自定义主题文件 theme.ts

import {createTheme} from '@mui/material/styles';

export function getCssVariable(variable: string): string {
    return getComputedStyle(document.documentElement).getPropertyValue(variable).trim();
}

declare module '@mui/material/styles' {
    interface BreakpointOverrides {
        xs: true;
        sm: true;
        md: true;
        lg: true;
        xl: true;
        xxl: true;
        xxxl: true;
    }
}

// 应用自定义主题
const theme = createTheme({
    cssVariables: true,
    breakpoints: {
        values: {
            xs: 0,
            sm: 600,
            md: 900,
            lg: 1200,
            xl: 1536,
            xxl: 1920,
            xxxl: 2200,
        },
    },
    palette: {
        primary: {
            // 测试时已替换为硬编码颜色,不再读取CSS变量
            main: '#153d77'
        }
    }
});

export default theme;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 00:30:00