javascript - 如何使用 Array 方法缩短 JSX 代码?

标签 javascript reactjs

我有一个 ProdSelectArr 组件。这个组件我用了三次,改了三次参数。本质上,我们可以说参数中只有值敏捷 prodSecKey 值发生变化,{arr1 arr2 arr3 setValue1 setValue2 setValue3} 交换位置。

<ProdSelectArr
        arr1={prod.color}
        arr2={prod.price}
        arr3={prod.saiz}
        setValue1={setCategColor}
        setValue2={setCategPrice}
        setValue3={setCategSaiz}
        setValueIndex={setIndexImgProd}
        value={categColor}
        headIndex={indexImgProd.headIndex}
        agility={prod.agility[0]}
        prodSecKey={0.1}
      />
       <ProdSelectArr 
        arr1={prod.price}
        arr2={prod.color}
        arr3={prod.saiz} 
        setValue1={setCategPrice}
        setValue2={setCategColor}
        setValue3={setCategSaiz}
        setValueIndex={setIndexImgProd}
        value={categPrice}
        headIndex={indexImgProd.headIndex}
        agility={prod.agility[1]}
        prodSecKey={0.2}
      />
       <ProdSelectArr
        arr3={prod.color}
        arr2={prod.price}
        arr1={prod.saiz}
        setValue3={setCategColor}
        setValue2={setCategPrice}
        setValue1={setCategSaiz}
        setValueIndex={setIndexImgProd}
        value={categSaiz}
        headIndex={indexImgProd.headIndex}
        agility={prod.agility[2]}
        prodSecKey={0.3}
      />

如何使用数组方法缩短代码?

最佳答案

对于交换,使用这样的东西:

function getItem(element, index) {
  const elementProps = {
    [`arr${index%3}`]: {prod.color},
    [`arr${(index+1)%3}`]: {prod.price},
    [`arr${(index+2)%3}`]: {prod.saiz},
    [`setValue${index%3}`]={setCategColor}
    [`setValue${(index+1)%3}`]={setCategPrice}
    [`setValue${(index+2)%3}`]={setCategSaiz}
    setValueIndex={setIndexImgProd}
    value={categColor}
    headIndex={indexImgProd.headIndex}
    agility={prod.agility[index]}
    prodSecKey: element/10
  }
  return <ProdSelectArr {...elementProps} />
}

您的数据:

let items = [1, 2, 3]

在你的 JSX 渲染中:

return <div>
    ...
    {items.map(getItem)}
    ...
</div>

关于javascript - 如何使用 Array 方法缩短 JSX 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56014981/

相关文章:

javascript - 如何使用 jQuery 过滤具有多个选择组的结果?

javascript - 如何通过 javascript 或 ionic 与 ADFS 3.0 对话?

javascript - 我有一个虚假数据对象,我想复制它,我该怎么做?

java - 如何显示html/rich格式的邮件?

javascript - Web Worker onMessage 在 IE11 中为 null

javascript - Material UI 断点设置方向 : portrait and landscape view

javascript - Draftjs 尝试删除原子 block

javascript - polymer 1.0 : Two-way bindings with input elements

javascript - 为什么当我更改状态时整页更新?

javascript - 在 React/TS 上调整窗口大小时调整图像大小、居中并保持纵横比