You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中使用Material UI实现如图所示的进度条?

解决Material UI自定义进度条不生效的问题

问题分析

你之前的代码核心问题是选择器写法错误:&.${linearProgressClasses.bar} 是给容器本身添加bar类的样式,但bar类实际是属于进度条内部的子元素,需要用后代选择器(加空格)才能选中它;另外,依赖colorPrimary类来设置背景的方式不够直接,容易因组件默认color属性变化失效。

修正后的实现方案

方案一:使用Styled组件

import { styled } from '@mui/material/styles';
import { LinearProgress, linearProgressClasses } from '@mui/material';

export const CustomLinearProgress = styled(LinearProgress)(({ theme }) => ({
  height: 35,
  borderRadius: 3,
  // 直接设置进度条容器的背景(未填充部分)
  backgroundColor: '#00b4e559',
  // 选中内部的bar元素,设置填充部分样式
  [`& .${linearProgressClasses.bar}`]: {
    borderRadius: 3,
    backgroundColor: '#00B4E5',
  },
}));

方案二:直接使用sx属性(更轻量化)

如果不想单独定义styled组件,也可以直接在组件上用sx属性快速定制:

import { LinearProgress } from '@mui/material';

// 使用示例
<LinearProgress
  variant="determinate"
  value={70} // 替换为你的进度值
  sx={{
    height: 35,
    borderRadius: 3,
    backgroundColor: '#00b4e559',
    '& .MuiLinearProgress-bar': {
      borderRadius: 3,
      backgroundColor: '#00B4E5',
    },
  }}
/>

使用说明

无论是哪种方案,都可以通过variant属性控制进度条类型(determinate为固定进度,indeterminate为加载动画),value属性设置具体进度百分比。

内容的提问来源于stack exchange,提问作者Kastriot Beha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:55:27