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

时间:2019-02-20 10:17:44

标签: 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}
  heading={Copy.three.heading}
 />

以上方法有效,但是有没有更有效的书写方式?我知道这可能不符合DRY方法!

4 个答案:

答案 0 :(得分:2)

  1. 创建一个包含string格式数字的数组
  2. 创建另一个数组,该数组将保存您的Step1, Step2, ... 变量
  3. Map将这些项放入基于先前描述的数组中的<Item>及其current string组成的index组件中

您将拥有类似这样的东西

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 :(得分: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道具的索引通常是一种反模式,尽管在这种情况下,手动构建数组不会造成任何问题。
另外,我不知道Step1Copy的去向及其格式,因此我只是手动构建了数组。也许您拥有的格式可以让您直接映射到某些列表并可以访问该信息。

答案 2 :(得分:0)

在不知道数据的确切结构或是否可以编辑结构的情况下,常见的模式是使用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>
   )
}

答案 3 :(得分:0)

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

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}
    />
})
相关问题