网站搜索

javascript - 编写多个 React 组件的更高效方法?


我有一个页面,在这里我渲染8个组件,唯一不同的是数值在迭代……

<Item
  classModifier="step"
  image={Step1}
  heading={Copy.one.heading}
 />
 <Item
  classModifier="step"
  image={Step2}
  heading={Copy.two.heading}
 />
 <Item
  classModifier="step"
  image={Step3}
  heading={Copy.three.heading}
 />

以上方法可行,但有没有更高效的写法?我意识到这可能不符合 DRY(不要重复自己)原则!

答案#1

  1. 创建一个包含你的数字的字符串格式的数组
  2. 创建另一个数组来存放你的 Step1, Step2, ... 变量
  3. 根据之前描述的数组中的current string及其index,将这些项目映射到<Item>组件中

你会有类似这样的东西

const numbers = ['one', 'two', 'three'];
const steps = [Step1, Step2, Step3];     // These need to be defined before

return (
  <div>
    {numbers.map((s, i) => (
      <Item key={i} classModifier='step' image={steps[i]} heading={Copy[s].heading}>
    ))}
  </div>
);

编辑

  • 这要求你的两个数组按相同的顺序排序。否则,它将无法将步骤与相应的编号匹配
  • 为了避免这种情况,你应该在数组中放置对象而不是原始字符串。查看 Gabriele 的回答,了解更健壮且可维护的实现方式

答案#2

你可以创建一个数组,并对其进行映射,返回组件

render(){
    const Items = [
      {step:Step1, heading: Copy.one.heading},
      {step:Step2, heading: Copy.two.heading},
      {step:Step3, heading: Copy.three.heading}
    ]

   
    return Items.map(({step, heading},index)=><Item 
      key={index}
      classModifier="step"
      image={step}
      heading={heading}
    />)
}

用于 key 属性的索引通常是一种反模式,尽管在这种手动构建数组的情况下,它应该不会造成任何问题。
另外,我不清楚 Step1 和 Copy 的来源及其格式,所以我只是手动构建了数组。也许你拥有的格式允许你直接对某个列表进行映射并访问该信息。