当前位置: 首页 > news >正文

前端react 实现分段进度条

一 效果如下

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

二 封装的源码如下

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>
  );
};

三 引用方式如下

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

 

相关文章:

  • Linux(25)——进程调度
  • SQL Server :可用性组 automatic seeding
  • Visual Studio Code配置自动规范代码格式
  • 大语言模型智体的综述:方法论、应用和挑战(上)
  • 随性研究c++-智能指针
  • 扫描仪+文档pdf编辑器+pdf格式转换器
  • 电力系统惯量及其作用解析
  • 移动端动态化建设的演进与实践:从技术革新到生态繁荣
  • DAY 33 leetcode 383--哈希表.赎金信 49--字母异位词分组
  • 如何本地部署RWKV-Runner尝鲜CPU版
  • odrive环境构筑问题
  • R语言绘图 | 使用scplotter包绘制细胞间通信图
  • 【超详细】一文解决更新澎湃2.0后LSPose失效问题
  • STM32 FATFS - 在flash上运行fatfs
  • 文章记单词 | 第15篇(六级)
  • Java笔记2——编程基础
  • 高效内存位操作:如何用C++实现数据块交换的性能飞跃?
  • STM32技能综合巩固
  • 使用 Vue 重构 RAGFlow 实现聊天功能
  • 第十二届蓝桥杯省赛软件类(cc++组)
  • 上海国际电影节将于6月3日公布排片表,6月5日中午开票
  • 再囤三个月库存!美国客户抢付尾款,外贸企业发货订单排到7月
  • 小米法务部:犯罪团伙操纵近万账号诋毁小米,该起黑公关案告破
  • “上海-日喀则”援藏入境旅游包机在沪首航
  • 去年上海全市博物馆接待观众约4087万人次,同比增31.9%
  • 2025年上海科技节开幕,人形机器人首次登上科学红毯