首页 > 解决方案 > 编写多个 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 方法!

标签: javascriptreactjstypescriptecmascript-6

解决方案


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

你会有这样的东西

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

编辑


推荐阅读