You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React/JavaScript进度条逻辑优化:解决代码重复问题

优化进度条组件的重复代码方案

看起来你现在的进度条组件因为硬编码不同price值的渲染逻辑,导致了大量重复的JSX结构,维护起来肯定很头疼。结合你提到的「接收数值范围+验证逻辑」的需求,这里有几个实用的优化思路,你可以参考:

1. 用配置数据驱动渲染(最推荐)

把不同price对应的进度条结构抽象成配置对象,这样新增或修改进度条样式时,只需要修改配置,不用重复写JSX:

const ProgressBar = ({ price }) => {
  // 定义进度条配置:key对应price值,value是需要渲染的percentage类名数组
  const progressConfig = {
    1: ['one', 'two'],
    2: ['one', 'two', 'three'], // 假设price=2时要渲染3个span
    // 可以继续扩展更多price对应的配置
  };

  // 验证price的有效性:判断是否在配置的key范围内
  const isValidPrice = Object.keys(progressConfig).includes(String(price));
  if (!isValidPrice) {
    return <div className="bar">无效的价格范围</div>; // 或者返回默认空进度条
  }

  const currentPercentages = progressConfig[price];

  return (
    <div className="bar">
      {currentPercentages.map((className, index) => (
        <span key={index} className={`percentage ${className}`} />
      ))}
    </div>
  );
};

2. 抽象单个进度条项组件

如果每个percentage元素还有额外的逻辑(比如点击事件、自定义属性),可以把它抽象成独立组件,进一步减少重复:

// 抽象的进度条项组件
const ProgressItem = ({ className }) => {
  // 这里可以添加单个进度项的通用逻辑,比如hover效果、点击事件等
  return <span className={`percentage ${className}`} />;
};

const ProgressBar = ({ price }) => {
  const progressConfig = {
    1: ['one', 'two'],
    2: ['one', 'two', 'three'],
  };

  const isValidPrice = Object.keys(progressConfig).includes(String(price));
  if (!isValidPrice) {
    return <div className="bar">无效的价格范围</div>;
  }

  return (
    <div className="bar">
      {progressConfig[price].map((className, index) => (
        <ProgressItem key={index} className={className} />
      ))}
    </div>
  );
};

3. 适配数值范围的场景(如果price是区间值)

你提到组件是「接收数值范围」的进度条,比如price可能是1-5这样的区间,而不是单个固定值。这时候可以把配置改成区间匹配的形式:

const ProgressBar = ({ price }) => {
  // 配置区间:min/max是数值范围,percentages是对应的进度项类名
  const rangeConfig = [
    { min: 1, max: 1, percentages: ['one', 'two'] },
    { min: 2, max: 3, percentages: ['one', 'two', 'three'] },
    { min: 4, max: 5, percentages: ['one', 'two', 'three', 'four'] },
  ];

  // 验证并匹配对应的区间配置
  const matchedConfig = rangeConfig.find(
    item => price >= item.min && price <= item.max
  );

  if (!matchedConfig) {
    return <div className="bar">无效的价格范围</div>;
  }

  return (
    <div className="bar">
      {matchedConfig.percentages.map((className, index) => (
        <span key={index} className={`percentage ${className}`} />
      ))}
    </div>
  );
};

这些方案的核心都是把可变的逻辑抽离成配置,让组件逻辑更通用,后续新增价格对应的进度条样式时,只需要修改配置即可,不用复制粘贴重复的JSX代码。

原代码片段:

const ProgressBar = ({ price }) => { return ( <div className="bar"> {price === 1 && ( <React.Fragment> <span className="percentage one" /> <span className="percentage two" /> </React.Fragment> )} {price === 2 && ( <React.Fragment> <span cla...

内容的提问来源于stack exchange,提问作者MontyGoldy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:35:17