【问题标题】:Using theme palette colors in custom MUI button variant在自定义 MUI 按钮变体中使用主题调色板颜色
【发布时间】:2021-11-04 20:45:04
【问题描述】:

我有一个 MUI 5 按钮变体,我想在其上使用现有的主题调色板颜色。我的appTheme.ts 设置如下:

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

declare module '@mui/material/Button' {
  interface ButtonPropsVariantOverrides {
    light: true;
  }
}

export const theme: Theme = createTheme({
  palette: {
    primary: {
      main: 'black',
      light: 'white',
    },
    secondary: {
      main: 'gray',
      light: 'white',
    },
    info: {
      main: 'white',
    },
    warning: {
      main: 'red',
    },
  },
  typography: {
    fontFamily: 'Lato',
  },
  components: {
    MuiButton: {
      variants: [
        {
          props: { variant: 'light', color: 'primary' },
          style: {
            textTransform: 'none',
            border: 'none',
            backgroundColor: 'primary.light',
            color: 'primary',
            borderRadius: 8,
            '&:hover': {
              backgroundColor: alpha('primary.main', 0.16),
              '&:active': {
                backgroundColor: alpha('primary.main', 0.32),
              },
            },
          },
        },
      ],
    },
  },
});

这有效,除了&:hover 状态属性,它对主题声明一无所知,因此MUI: Unsupported 'primary.main' color. 出错

有没有办法可以在主题声明中使用这样的主题颜色,或者我是否在主题包装级别上覆盖它?我发誓我在某处的一些文档中看到了这个,但找不到它。

【问题讨论】:

    标签: javascript reactjs typescript material-ui


    【解决方案1】:

    这里的问题是,您试图在主题覆盖定义中引用主题调色板颜色,这会导致问题。所以alpha方法参数是无法识别的。

    要访问您的主题调色板颜色,请先单独定义它,然后再访问它。

    const globalTheme = createTheme({
      palette: {
        primary: {
          main: purple[500]
        },
        secondary: {
          main: "#11cb5f"
        }
      }
    });
    
    const theme = createTheme(
      {
        components: {
          MuiButton: {
            variants: [
              {
                props: { variant: "text", color: "primary" },
                style: {
                  textTransform: "none",
                  border: "none",
                  backgroundColor: globalTheme.palette.primary.light,
                  color: "#fff",
                  borderRadius: 8,
                  "&:hover": {
                    color: globalTheme.palette.primary.light,
                    backgroundColor: alpha(globalTheme.palette.primary.main, 0.16)
                  },
                  "&:active": {
                    backgroundColor: globalTheme.palette.primary.dark,
                    color: "#fff"
                  }
                }
              }
            ]
          }
        }
      },
      globalTheme
    );
    
    

    在此处查看工作示例 - https://codesandbox.io/s/mui-button-variant-override-e18vg

    【讨论】:

    • 啊,很有创意!为了完整起见,您可能希望将演示完全复制到此处,以便说明如何组合全局主题和导出组合主题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2021-12-01
    • 2020-08-13
    • 2018-05-28
    • 2021-06-10
    相关资源
    最近更新 更多