如何在Material UI中为LinearProgress应用自定义主题调色板颜色?
问题描述
我已通过createTheme为代码库设置了如下主题:
import { createTheme } from '@mui/material/styles'; export default function getTheme() { return { theme: createTheme({ palette: { ..., progress: { 0: '#000000', 126: '#222222', 251: '#444444', 376: '#666666', 501: '#888888', 626: '#aaaaaa', 751: '#cccccc', 876: '#eeeeee', 1000: '#ffffff', }, ..., } }); } }
该主题在Typography组件中可正常使用:
import { Typography } from '@mui/material'; export default function HelloWorld() { return ( <Typography color="progress.126"> Hello World </Typography> ); }
但将其应用于LinearProgress组件时,会抛出TypeError: Cannot read properties of undefined (reading 'main')错误:
import { LinearProgress } from '@mui/material'; export default function ProgressBar() { return ( <LinearProgress variant="determinate" value={50} color="progress.501" sx={{ height: 8, width: 120, }} /> ); }
请问如何像使用其他Material UI组件一样,将这些自定义颜色应用到LinearProgress组件上?
解决方案
问题出在LinearProgress的color属性逻辑上:它只认内置颜色键(比如primary、secondary),或者要求颜色对象包含main这类属性,而你定义的progress下的颜色是直接的十六进制值,不符合它的读取规则。
下面是两种可行的解决办法:
方法一:用sx属性直接引用主题颜色
直接在sx里获取主题中的自定义颜色,覆盖进度条的进度条颜色:
import { LinearProgress } from '@mui/material'; export default function ProgressBar() { return ( <LinearProgress variant="determinate" value={50} sx={{ height: 8, width: 120, '& .MuiLinearProgress-bar': { backgroundColor: theme => theme.palette.progress[501] } }} /> ); }
方法二:扩展主题让LinearProgress支持自定义颜色
如果想保持和Typography一样的使用方式,直接通过color属性调用,需要在主题中为LinearProgress添加自定义颜色的样式映射:
import { createTheme } from '@mui/material/styles'; export default function getTheme() { return { theme: createTheme({ palette: { ..., progress: { 0: '#000000', 126: '#222222', 251: '#444444', 376: '#666666', 501: '#888888', 626: '#aaaaaa', 751: '#cccccc', 876: '#eeeeee', 1000: '#ffffff', }, ..., }, components: { MuiLinearProgress: { styleOverrides: { root: ({ ownerState, theme }) => { const color = ownerState.color; if (color?.startsWith('progress.')) { const colorKey = color.split('.')[1]; return { '& .MuiLinearProgress-bar': { backgroundColor: theme.palette.progress[colorKey] } }; } return {}; } } } } }); } }
修改后,你就能像之前那样用color="progress.501"给LinearProgress设置颜色了。
内容的提问来源于stack exchange,提问作者Renan Elfo
相关产品推荐
相关产品推荐

