如何为每两个元素进行映射以进行反应? [英] How do I map for every two elements for react?
问题描述
假设我有一个如下所示的数组:
Let's say I have an array that looks like this:
const array = [0, 1, 2, 3, 4, 5, 6, 7]
我想要做的是对 .map 函数中的每 2 个对象进行迭代,但它需要在我的渲染中看起来像这样(请注意,我使用的是 React Bootstrap):
What I'm trying to do is iterate for every 2 objects in a .map function, but it needs to look like something like this in my render (note that I'm using React Bootstrap):
<Row>
<Col>array[0]</Col>
<Col>array[1]</Col>
</Row>
<Row>
<Col>array[2]</Col>
<Col>array[3]</Col>
</Row>
等等...
因此,对于每 2 个对象,它需要有自己的行,然后在关闭 Row 之前渲染这 2 个对象,如果有更多元素,则开始新的 Row.
So for every 2 objects, it needs to have it's own row, and then render those 2 objects before closing a Row and starting a new Row if it has more elements.
实现这一目标的最佳方法是什么?
What's the best way to achieve this?
推荐答案
简答
转换模型,然后注入视图.
short answer
Transform model, then inject in View.
您需要根据需要将数组转换为矩阵:
You need to convert your array to a matrix as per your need:
const array = [0, 1, 2, 3, 4, 5, 6, 7]
const rows = array.reduce(function (rows, key, index) {
return (index % 2 == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows;
}, []);
console.log(rows)
现在,您的模型已转换为这种格式
Now, you have your model is converted to this format
[ [0, 1] , [2, 3] , [4, 5] , [6, 7] ]
现在嵌套循环应该优雅地完成工作:
Now nested loop should do the job with elegance :
rows.map(row => (
<Row >
{ row.map(col => (<Col>{col}</Col>)) }
</Row>
))
注意:
这个优雅的解决方案背后的工程是准备你的模型,然后你循环.
NOTES:
The engineering behind this elegant solution is to prepare your model, then you loop.
不确定,当组件在循环中呈现时,React 是否仍然需要 id (.e.g:
)..
Not sure, if React still requires id in (.e.g: <Compo id="">
) when components are rendered in loop..
这篇关于如何为每两个元素进行映射以进行反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!