【问题标题】:Add alpha for all variants in MUI Theme - React为 MUI 主题中的所有变体添加 alpha - React
【发布时间】:2023-01-19 19:10:20
【问题描述】:

我有一个 MUI 主题设置,我想向 MuiChip 添加 alpha 颜色。我不确定如何访问 createTheme 中的特定颜色。例如,如果我的主色是“#FF0000”,辅助色是“#00ff00”,那么对于 MuiChip,我想做 backgroundColor: alpha(theme.palette, 0.1);如果我为 chip 组件传递一个 variant prop,则 backgroundColor 应该更改为该变体的 alpha 版本。

    export const theme = createTheme({
      palette: {
        primary: {
          main: colors.primary,
        },
        secondary: {
          main: colors.secondary,
        },
        error: {
          main: colors.red,
        },
      },
      components: {
        
        MuiChip: {
          styleOverrides: {
            colorPrimary: {
              color: 'white',
            },
            root: {
                backgroundColor: alpha(theme.palette, 0.1)
            }
          },
        },
      },
    });

请指教。

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    正如我所见,您的 theme 误解了 MUI 如何与主题一起工作。我看到了这个主要问题:

    • 如果仅使用 MUI colors.primary 无效。您必须使用准确的颜色代码,例如 #fff。 (如果您使用某种color lib,则不正确)
    • styleOverrides 中,您必须使用文档here 中的模板。有了这个,您将获得 themeownerState 来在 CSS 级别上操作组件。
    • theme.palette 不是您应该在 alpha() 中使用 theme.palette.primary.main 的确切颜色参考
    • 您可以使用alpha,但我认为opacity更简单
    • 仅供此处其他读者参考,我们可以找到 CSS reference of Chip component 以覆盖规则名称。

    我在Codesandbox, you can try it 上做了一个工作代码。

    这是我解决问题的主题:

    export const theme = createTheme({
      palette: {
        primary: {
          main: "#a0a"
        },
        secondary: {
          main: "#0a0"
        },
        error: {
          main: "#a00"
        }
      },
      components: {
        MuiChip: {
          styleOverrides: {
            root: {
              color: "#0a0"
            },
            colorSuccess: ({ ownerState, theme }) => ({
              ...(ownerState.variant === "custom" && {
                backgroundColor: alpha(theme.palette.primary.main, 0.3)
              })
            })
          }
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2021-12-06
      • 2022-01-04
      • 2022-08-18
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多