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

Material UI自定义主题颜色赋值Button出现TypeScript报错咨询

报错原因

你遇到的TypeScript报错本质是MUI默认的Button组件color属性类型定义仅支持内置的7种枚举值:inherit/primary/secondary/success/error/info/warning,并不是功能层面不支持自定义颜色,你可以通过两种方案解决问题:


解决方案

  • 方案1:扩展MUI类型定义,直接用color属性传入自定义颜色key
    首先在全局类型声明文件(比如src/mui.d.ts)中新增以下类型扩展:

    import '@mui/material/styles';
    import '@mui/material/Button';
    
    // 扩展主题调色板类型
    declare module '@mui/material/styles' {
      interface Palette {
        lightGrey: PaletteColor;
      }
      interface PaletteOptions {
        lightGrey?: PaletteColorOptions;
      }
    }
    
    // 扩展Button支持的color属性值
    declare module '@mui/material/Button' {
      interface ButtonPropsColorOverrides {
        lightGrey: true;
      }
    }
    

    之后在创建自定义主题时正确配置palette.lightGrey的颜色参数,就可以直接在Button上写color="lightGrey",MUI会自动读取主题中的对应颜色配置,不需要手动传入theme.palette.lightGrey。
    另外注意你当前代码里的pallete是拼写错误,正确拼写为palette,也可能是报错的诱因之一。

  • 方案2:通过样式属性直接设置颜色,无需扩展类型
    如果你不想修改全局类型定义,可以直接通过sx属性、styled组件或者内联样式传入自定义颜色,示例写法:

    <Button sx={{ color: theme.palette.lightGrey.main }}>按钮</Button>
    

    这种方式不受color属性的类型限制,可以直接传入任意颜色值。


内容的提问来源于stack exchange,提问作者Sergiu Tonț

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:09:01