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

MUI主题定制:如何通用访问color属性为新按钮变体设样式?

MUI按钮Dashed变体动态颜色配置问题

我正在为MUI按钮创建一个新的dashed变体,希望将color属性指定的颜色同时应用为边框和文字颜色。

MUI官方文档提供的方法不够通用/动态,因为需要单独处理每一种可用颜色:

const theme = createTheme({
  components: {
    MuiButton: {
      variants: [
        {
          props: { variant: 'dashed' },
          style: {
            textTransform: 'none',
            border: `2px dashed ${blue[500]}`,
          },
        },
        {
          props: { variant: 'dashed', color: 'secondary' },
          style: {
            border: `4px dashed ${red[500]}`,
          },
        },
      ],
    },
  },
});

我期望的解决方案如下:

styleOverrides: {
      root: ({ ownerState, theme }) => ({
        ...(ownerState.variant === 'dashed' && {
          borderColor: theme.palette[ownerState.color || 'primary'].main
        }),
      }),
    },

但代码中theme.palette[ownerState.color || 'primary'].main这一行出现TypeScript错误:

Element implicitly has an 'any' type because expression of type 'OverridableStringUnion<"inherit" | "primary" | "secondary" | "success" | "error" | "info" | "warning", ButtonPropsColorOverrides>' can't be used to index type 'Palette'.

且将color设为inherit无法得到正确颜色。

补充说明:

我目前采用了一种需要在TypeScript中定义新类型来指定可用值的解决方案,但并不完全满意,仍期待更优方案。

内容的提问来源于stack exchange,提问作者mirja-t

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:17:09