前端react 实现分段进度条

一 效果如下

其中,前四段是有效值,后面灰色是剩余值。

二 封装的源码如下

javascript 复制代码
const ProgressBar = ({segments}: any) => {
  // 默认值和数据校验
  const validSegments = (segments || []).slice(0, 4).map((seg: any) => {
    return ({
      color: seg?.color || '#1890ff',
      percent: Math.max(0, Math.min(100, Number(seg?.percent) || 0))
    })
  });

  // 计算前四段总和
  const completedPercent = validSegments.reduce((sum: any, {percent}: { percent: any }) => {
    return sum + percent
  }, 0);

  // 计算剩余百分比(第五段)
  const remainingPercent = Math.max(0, 100 - completedPercent);

  // 构建五段数据(前四段+剩余段)
  const allSegments = [
    ...validSegments,
    {color: '#f0f0f0', percent: remainingPercent} // 灰色表示未完成部分
  ].filter(seg => seg.percent > 0); // 只显示有值的段

  return (
    <div style={{
      display: 'flex',
      width: '100%',
      height: 10,
      borderRadius: 6,
      overflow: 'hidden' // 关键:确保圆角生效
    }}>
      {allSegments.map(({color, percent}, index) => (
        <div
          key={index}
          style={{
            width: `${percent}%`,
            height: '100%',
            position: 'relative',
            marginRight: index === allSegments.length - 1 ? 0 : 2,
          }}
        >
          {/* 使用自定义div替代Progress实现圆角 */}
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              backgroundColor: color,
              // 圆角逻辑
              borderTopLeftRadius: index === 0 ? 6 : 0,
              borderBottomLeftRadius: index === 0 ? 6 : 0,
              borderTopRightRadius: index === allSegments.length - 1 ? 6 : 0,
              borderBottomRightRadius: index === allSegments.length - 1 ? 6 : 0,
            }}
          />
        </div>
      ))}
    </div>
  );
};

三 引用方式如下

javascript 复制代码
<ProgressBar
  segments={[
    {color: '#1677FFFF', percent: 10},
    {color: '#FAC414FF', percent: 15},
    {color: '#F56C22FF', percent: 40},
    {color: '#52C41AFF', percent: 10},
  ]}
/>

 
相关推荐
littleplayer8 分钟前
iOS Swift Redux 架构详解
前端·设计模式·架构
工呈士13 分钟前
HTML 模板技术与服务端渲染
前端·html
皮实的芒果14 分钟前
前端实时通信方案对比:WebSocket vs SSE vs setInterval 轮询
前端·javascript·性能优化
鹿九巫14 分钟前
【CSS】层叠,优先级与继承(三):超详细继承知识点
前端·css
奕云15 分钟前
react-redux源码分析
前端
咸鱼一号机16 分钟前
:global 是什么
前端
专业掘金17 分钟前
0425 手打基础丸
前端
五号厂房17 分钟前
Umi Max 如何灵活 配置多环境变量
前端
红尘散仙19 分钟前
六、WebGPU 基础入门——Vertex 缓冲区和 Index 缓冲区
前端·rust·gpu
南望无一19 分钟前
webpack性能优化和构建优化
前端·webpack