我试图通过同时映射多个道具来渲染子组件。我想做的是:
const Parent = props => {
const whatever = props.(***need to pass both props***).map((firstProp, secondProp) => (
<Child
key={//}
firstProp={firstProp}
secondProp={secondProp}
/>
));
return (
<div>
{whatever}
</div>
);
}
什么是正确的方法?
答案 0 :(得分:0)
您可以简单地映射第一个数组并使用索引,获取第二个数组的详细信息
const Parent = props => {
const whatever = props.firstPropsArray.map((firstProp, index) => (
<Child
key={//}
firstProp={firstProp}
secondProp={secondPropsArray[index]}
/>
));
return (
<div>
{whatever}
</div>
);
}
否则,您可以预处理数组以使用两个道具的值生成一个数组
const Parent = props => {
const mergedProps = props.firstPropsArray.map((first, index) => ([first, secondPropsArray[index]]));
const whatever = mergedProps.map(([firstProp, secondProp]) => (
<Child
key={//}
firstProp={firstProp}
secondProp={secondProp}
/>
));
return (
<div>
{whatever}
</div>
);
}
答案 1 :(得分:0)
映射数组时,您将获得第二个参数作为数组的索引,相反,您可以这样做
const Parent = props => {
const whatever = props.(***need to pass both props***).map((firstProp, i) => (
<Child
key={//}
firstProp={firstProp}
secondProp={secondProp[i]}
/>
));
return (
<div>
{whatever}
</div>
);