在 MUI 主题中使用自定义颜色架构

use*_*695 2 javascript reactjs material-ui

我想在我的主题中配置一些颜色,这些颜色由我的应用程序中的某些类别使用​​。

所以我设置了一个主题并在我的组件中使用它。

主题.tsx

import { createTheme, Theme } from '@mui/material/styles'
import { red } from '@mui/material/colors'

export const theme: Theme = createTheme({
  palette: {
    primary: {
      main: blue[800]
    },
    secondary: {
      main: '#19857b'
    },
    cat1: {
      main: red[700]
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

圆.tsx

import CircleIcon from '@mui/icons-material/FiberManualRecord'
import {theme} from '/shared/theme'

export function Circle() {
  return (
    <>
    <CircleIcon style={{ color: theme.palette.cat1.main }} />
    <CircleIcon style={{ color: theme.palette.cat1[200] }} />
    </>
  )
}
Run Code Online (Sandbox Code Playgroud)

我试图实现的是以动态方式设置某些元素的颜色。因此类别 1 中的圆将变为红色。所有需要的颜色都导入到主题中。我不想在组件本身中导入所有可能的颜色。

但我还想基于此计算另一个元素的颜色。在上面的例子中我想要得到 200 的红色。

Nea*_*arl 7

首先,不要使用styles,它更难覆盖,并且 MUI 有更好的替代方案(sxprop/ styledfunction ),它们theme在作为回调传递时为您提供对象,因此将代码更改为:

<CircleIcon sx={{ color: theme => theme.palette.cat1.main }} />
Run Code Online (Sandbox Code Playgroud)

其次,如果您想访问颜色的其他变体,例如使用primary或secondary,请使用augmentColor()函数告诉 MUI自动为您生成dark//颜色:lightcontrastText

import {
  createTheme,
  ThemeProvider,
  Theme,
  lighten,
  darken
} from "@mui/material/styles";

const { palette } = createTheme();
const { augmentColor } = palette;
createTheme({
  palette: {
    // this will tell MUI to calculate the main, dark, light and contrastText
    // variants based on the red[500], and then merge the new properties with
    // the color object itself. The end result will be something like:
    // cat1: { '100': ..., '900': ..., light: ..., dark: ..., contrastText: ... }
    cat1: augmentColor({ color: red }),

    // this will tell MUI to calculate the main, dark, light and contrastText
    // variants based on the red[100], no other shades are passed unlike the above.
    cat2: augmentColor({ color: { main: red[100] } })

    // light and dark variants are generated in augmentColor using lighten() and
    // darken() function, if you want even more control, override the light and
    // dark properties yourself like this:
    cat3: augmentColor({
      color: {
        dark: darken(red[300], 0.6),
        main: red[300],
        light: lighten(red[300], 0.6)
      }
    })
  }
})
Run Code Online (Sandbox Code Playgroud)

现场演示

Codesandbox 演示