Me gustaría configurar algunos colores en mi tema, que son utilizados por algunas categorías en mi aplicación.
Así que configuré un tema y lo uso en mi componente.
tema.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] } } })círculo.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] }} /> </> ) }Lo que trato de lograr es establecer el color de algunos elementos de forma dinámica. Entonces, el Círculo en la categoría 1 obtendrá el color rojo. Todos los colores que se necesitan se importan en el tema. No quiero importar todos los colores posibles en el componente mismo.
Pero también quiero calcular el color de otro elemento basado en esto. En el ejemplo anterior, me gustaría obtener 200 de rojo.
En primer lugar, no use styles , es más difícil de anular y MUI tiene mejores alternativas (función sx prop/ styled ) que le proporcionan el objeto del theme cuando lo pasa como una devolución de llamada, así que cambie su código a:
<CircleIcon sx={{ color: theme => theme.palette.cat1.main }} /> En segundo lugar, si desea acceder a otras variantes del color como lo que puede con primary o secondary , use la función augmentColor() para indicarle a MUI que genere los colores dark / light / contrastText del texto automáticamente para usted:
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) } }) } })