如何修改Material-UI LinearProgress加载进度条的颜色?
求助:修改加载进度条颜色
我尝试用withStyle、CSS修改加载进度条的颜色,但都没生效,找不到有效解决方法,恳请有人协助。
我的代码片段:
<Box sx={{ width: '100%'}}> {progress < 100 && <LinearProgressWithLabel value={progress} style={{background: "yellow"}} />} </Box>
解决方法
针对Material UI的LinearProgressWithLabel组件,直接用style属性无法覆盖内部进度条样式——因为组件自带的CSS-in-JS样式优先级更高,你可以试试以下几种方式:
1. 用sx属性直接覆盖内部样式
通过sx传入类选择器,精准修改进度条的填充色和背景色:
<LinearProgressWithLabel value={progress} sx={{ // 修改进度条的填充颜色 '& .MuiLinearProgress-bar': { backgroundColor: 'yellow', }, // 修改进度条的背景底色 '& .MuiLinearProgress-root': { backgroundColor: '#e5e5e5', } }} />
2. 自定义LinearProgressWithLabel组件
如果LinearProgressWithLabel是你自己封装的组件,直接在内部给LinearProgress设置样式:
function LinearProgressWithLabel(props) { return ( <Box sx={{ display: 'flex', alignItems: 'center' }}> <Box sx={{ width: '100%', mr: 1 }}> <LinearProgress {...props} sx={{ backgroundColor: '#e5e5e5', // 背景底色 '& .MuiLinearProgress-bar': { backgroundColor: 'yellow', // 进度填充色 } }} /> </Box> <Box sx={{ minWidth: 35 }}> <Typography variant="body2" color="text.secondary"> {`${Math.round(props.value)}%`} </Typography> </Box> </Box> ); }
3. 全局主题配置(适合全项目统一修改)
通过Material UI的主题配置,一次性修改所有线性进度条的样式:
import { createTheme, ThemeProvider } from '@mui/material/styles'; const customTheme = createTheme({ components: { MuiLinearProgress: { styleOverrides: { root: { backgroundColor: '#e5e5e5', }, bar: { backgroundColor: 'yellow', }, }, }, }, }); // 在项目根组件中使用主题 function App() { return ( <ThemeProvider theme={customTheme}> {/* 你的页面/组件 */} </ThemeProvider> ); }
内容的提问来源于stack exchange,提问作者Juniour Developer
相关产品推荐
相关产品推荐

