Javascript 编写多个React组件的更有效方法?

Javascript 编写多个React组件的更有效方法?,javascript,reactjs,typescript,ecmascript-6,Javascript,Reactjs,Typescript,Ecmascript 6,我有一个页面,其中我呈现8个组件,唯一不同的是一个值迭代 <Item classModifier="step" image={Step1} heading={Copy.one.heading} /> <Item classModifier="step" image={Step2} heading={Copy.two.heading} /> <Item classModifier="step" image={Step3} h

我有一个页面,其中我呈现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}
 />
以上这些都是有效的,但是有没有更有效的方法来写这篇文章呢?我知道这可能不符合干法

创建一个以字符串格式包含数字的数组 创建另一个数组,该数组将容纳步骤1、步骤2。。。变量 根据前面描述的数组中的当前字符串及其索引,将这些项转换为组件 你会有这样的东西

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>
);
编辑 这要求两个数组按相同的顺序排序。否则,它将无法将步骤与其对应的编号匹配 避免在数组中放置对象而不是原始字符串。
您可以创建一个数组并在其上映射返回组件

渲染{ 常数项=[ {步骤:步骤1,标题:Copy.one.heading}, {步骤:步骤2,标题:Copy.two.heading}, {步骤:步骤3,标题:Copy.three.heading} ] 返回项。映射{步骤,标题},索引=>
} 如果不知道数据是如何构造的,或者您是否可以编辑结构,一种常见的模式是使用map

render(){
   const data = [
      {
         image: "a.jpg",
         heading: "A",
         key: 0
      }, 
      {
         image: "b.jpg",
         heading: "B",
         key: 1
      }
   ];
   const someComponents = data.map(d => (
      <Item key={d.key} classModifier="step" image={d.image} />
   ));
   return (
      <div>{someComponents}</div>
   )
}

将数据和视图分开。并通过迭代数据来呈现视图

data = [
    { image: Step1, heading: Copy.one.heading },
    { image: Step2, heading: Copy.two.heading },
    { image: Step3, heading: Copy.three.heading },
]
data.map((obj, index) => {
    return <Item
        key={index}
        classModifier="step"
        image={obj.index}
        heading={obj.heading}
    />
})

您可能应该将两个数组合并为一个。拥有两个需要匹配其顺序的数组不是一个好模式。是的,这是正确的方法,即使这样做有效。我加入了一个链接到你的答案,而不是编辑我的,因为那样的话,它会和你第一次想到的完全一样