gpt4 book ai didi

javascript - 如何为每两个元素映射以进行 react ?

转载 作者:行者123 更新时间:2023-12-05 00:34:40 26 4
gpt4 key购买 nike

假设我有一个如下所示的数组:

const array = [0, 1, 2, 3, 4, 5, 6, 7]
我想要做的是迭代 .map 函数中的每 2 个对象,但它需要在我的渲染中看起来像这样(注意我正在使用 React Bootstrap):
<Row>
<Col>array[0]</Col>
<Col>array[1]</Col>
</Row>


<Row>
<Col>array[2]</Col>
<Col>array[3]</Col>
</Row>
ETC...
因此,对于每 2 个对象,它需要拥有自己的行,然后在关闭 Row 之前渲染这 2 个对象,如果它有更多元素则开始新 Row。
实现这一目标的最佳方法是什么?

最佳答案

简短的回答
转换模型,然后注入(inject) View 。
详细回答
您需要根据需要将数组转换为矩阵:

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)

现在,您已将模型转换为这种格式 [ [0, 1] , [2, 3] , [4, 5] , [6, 7] ] 现在嵌套循环应该优雅地完成这项工作:
rows.map(row => ( 
<Row >
{ row.map(col => (<Col>{col}</Col>)) }
</Row>
))

笔记:
这个优雅的解决方案背后的工程是准备你的模型,然后你循环。
不确定,当组件在循环中呈现时,React 是否仍然需要 id(例如: <Compo id="">)。

关于javascript - 如何为每两个元素映射以进行 react ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62880615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com