前端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 分钟前
vue+微信小程序 五角星
前端·vue.js·微信小程序
GISer_Jing1 小时前
React手撕组件和Hooks总结
前端·react.js·前端框架
Warren985 小时前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
mCell6 小时前
JavaScript 运行机制详解:再谈 Event Loop
前端·javascript·浏览器
amy_jork8 小时前
npm删除包
开发语言·javascript·ecmascript
帧栈10 小时前
开发避坑指南(27):Vue3中高效安全修改列表元素属性的方法
前端·vue.js
max50060010 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
excel10 小时前
使用函数式封装绘制科赫雪花(Koch Snowflake)
前端
我命由我1234510 小时前
软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)
java·开发语言·javascript·设计模式·java-ee·策略模式·js
萌萌哒草头将军11 小时前
Node.js v24.6.0 新功能速览 🚀🚀🚀
前端·javascript·node.js