我有一个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}
/>
如何使用Array方法缩短代码?
答案 0 :(得分:1)
要进行交换,请使用以下内容:
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>
答案 1 :(得分:0)
我认为您需要的是HOC方法,然后考虑基于数组的解决方案:
const HocProdSelectArr = (props) => {
return <ProdSelectArr
arr1={props.arr1}
arr2={props.arr2}
arr3={props.arr3}
setValue1={setCategColor}
setValue2={setCategPrice}
setValue3={setCategSaiz}
setValueIndex={setIndexImgProd}
value={categColor}
headIndex={indexImgProd.headIndex}
agility={props.agility}
prodSecKey={props.prodSecKey}
/>
}
<HocProdSelectArr
arr1={prod.color}
arr2={prod.price}
arr3={prod.saiz}
agility={prod.agility[0]}
prodSecKey={0.1}
/>
<HocProdSelectArr
arr1={prod.price}
arr2={prod.color}
arr3={prod.saiz}
agility={prod.agility[1]}
prodSecKey={0.2}
/>
<HocProdSelectArr
arr1={prod.saiz}
arr2={prod.price}
arr3={prod.color}
agility={prod.agility[2]}
prodSecKey={0.3}
/>
答案 2 :(得分:0)
在您的渲染函数内部:
render() {
return (
{
prod.agility.map( ( agility, index ) => {
return (
<ProdSelectArr
arr1={prod.color}
arr2={prod.price}
arr3={prod.saiz}
setValue1={setCategColor}
setValue2={setCategPrice}
setValue3={setCategSaiz}
setValueIndex={setIndexImgProd}
value={categColor}
headIndex={indexImgProd.headIndex}
agility={agility}
/* if you have secrets array you can do: secrets[index] */
/* if you want your secret to be 1 tenth of index value, use below */
prodSecKey={ index / 10 }
/>
)
})
}
)
}