[英]React map to render with row
嗨,我有一个包含 6 个元素的数组,并通过将数组划分为三个元素来使用 map 函数在每行中迭代 3 个元素,我不会在不划分数组的情况下执行此操作,我的代码如下
<div
style={{
width: "100%",
display: "flex",
flexWrap: "wrap",
justifyContent: "space-around",
}}
>
{array1.map((item, index) => {
return (
<div className="col-4">
<img src={item.icon} />
<p >{item.title}</p>
<p >
{item.description}
</p>
</div>
);
})}
</div>
<div
style={{
width: "100%",
display: "flex",
flexWrap: "wrap",
justifyContent: "space-around",
}}
>
{array2.map((item) => {
return (
<div className="col-4 item-item">
<img src={item.icon} />
<p>{item.title}</p>
<p>
{item.description}
</p>
</div>
);
})}
</div>
我想每行映射 3 个元素,而不将 6 个元素数组划分为 3 个元素,感谢您的建议
我建议您在此处使用此函数将数组拆分为多个块。 从那里您可以执行嵌套地图!
// # Source https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/chunk.md
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
console.log(chunk([1, 2, 3, 4, 5,6], 3));
// Output - [[1,2,3],[4,5,6]]
考虑到您已经知道数组的长度为 6。假设数组名称为“originalArray”
<div
style={{
width: "100%",
display: "flex",
flexWrap: "wrap",
justifyContent: "space-around",
}}
>
{originalArray.map((item, index) => {
(index<3)?
return (
<div className="col-4">
<img src={item.icon} />
<p >{item.title}</p>
<p >
{item.description}
</p>
</div>
}
: return( <div className="col-4 item-item">
<img src={item.icon} />
<p>{item.title}</p>
<p>
{item.description}
</p>
</div>)
);
})}
</div>
您可以为此目的使用地图
array.map((element, index) => {
if (index % 3 === 0)
return (
<div className="row">
<div className="col">{array[index]}</div>
<div className="col">{array[index + 1]}</div>
<div className="col">{array[index + 2]}</div>
</div>
);
})
如果您决定更改每行的元素数,则只需调整值即可。
我不确定这个片段的性能,但你可以用reduce
而不是map
来实现你想要的
array.reduce<JSX.Element[]>((rows, item, itemIndex) => {
const ComponentToRender = <Component />
if (itemIndex % 3 === 0) {
rows.push(<Row key={rows.length + 1}>{ComponentToRender}</Row>);
} else {
const LastRow = rows[rows.length - 1];
const cols = [
...React.Children.toArray(LastRow.props.children),
ComponentToRender,
];
rows[rows.length - 1] = <Row key={rows.length + 1}>{cols}</Row>;
}
return rows;
}, [])
或者只是使用 CSS 网格系统来渲染每行 3 个元素。 这样你就可以坚持使用简单的map
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.