前端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},
  ]}
/>

 
相关推荐
计算机魔术师1 分钟前
Anthropic 发布电商 Agent 架构与生产实践指南,并开源 commerce-agents 参考实现
前端
IMPYLH10 分钟前
HTML 的 <ol> 元素
前端·html
IMPYLH11 分钟前
HTML 的 <object> 元素
前端·html
DevOpenClub12 分钟前
PDF 多格式解析如何避免混用输出:TEXT、HTML、XML 与 TAG 数据契约
xml·前端·数据库·pdf·html
meilindehuzi_a20 分钟前
从域名到数据库:React + Node.js 项目部署全流程与用户访问链路
数据库·react.js·node.js
用户2526327534721 分钟前
请问同一台服务器能同时部署前后端项目并支持https吗?
前端
小凯在掘金32 分钟前
类型判断什么时候用 typeof?
javascript
Sincerelyplz34 分钟前
【Pipecat】基于Pipecat的voice agent实践
前端·后端·agent
lerhxx38 分钟前
为什么你的Three.js物体总是乱转?一文彻底搞懂“万向锁”与四元数
前端·three.js
幸运小圣41 分钟前
JavaScript 关键字与保留字学习笔记详细讲解,一篇get ✅【JavaScript查缺补漏】
javascript·笔记·学习