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

 
相关推荐
front_explorers2 分钟前
Umi项目必看,从Webpack到Rspack,KMI引领性能革命🚀
前端
旺仔牛仔QQ糖3 分钟前
都写那么多项目了, 傻傻分不清楚NODE_ENV 和 模式(Mode) 两者区别是什么
前端·面试
xcLeigh8 分钟前
HTML5实现简洁的体育赛事网站源码
前端·html
渔舟唱晚@11 分钟前
Axios 取消请求的演进:CancelToken vs. AbortController
javascript
棉花糖超人11 分钟前
【从0-1的CSS】第1篇:CSS简介,选择器已经常用样式
前端·css
GISer_Jing16 分钟前
XHR / Fetch / Axios 请求的取消请求与请求重试
前端·javascript·网络
天涯学馆19 分钟前
微前端架构设计:从理论到实践的全面指南
前端·javascript·面试
Verin31 分钟前
Next.js+Wagmi+rainbowkit构建以太坊合约交互模版
前端·web3·以太坊
KenXu33 分钟前
🚀 Cursor 1.0 重磅发布!AI代码编辑器迎来革命性升级
前端
凌辰揽月35 分钟前
Web后端基础(Maven基础)
前端·pycharm·maven