大佬教程收集整理的这篇文章主要介绍了如何包装由对象数组填充的元素成对,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
具有以下对象数组:
const items = [
{
description = 'first description'
},{
description = 'second description'
},{
description = 'third description'
},{
description = 'fourth description'
},...
]
使用地图很容易表示描述:
{
items.map((item) => (
<div>item.description</div>
));
}
将输出以下内容:
<div>first description</div>
<div>second description</div>
<div>third description</div>
<div>fourth description</div>
...
但是我需要为每对元素添加一个容器,所以输出应该是这样的:
<div classname="container">
<div>first description</div>
<div>second description</div>
</div>
<div classname="container">
<div>third description</div>
<div>fourth description</div>
</div>
...
@R_317_10673@下解决方案,但理解起来很复杂,我认为必须有一个更清晰的解决方案:
{
let result = [];
let counter = 0;
items.forEach((item,indeX) => {
if (items.length / 2 > indeX) {
result[index] = (
<div classname="container">
<div>items[counter]</div>
<div>items[counter+1]</div>
</div>
);
counter = counter + 2;
}
})
}
{result.map((item) => item)}
有什么建议吗?
这里有一个更简洁的解决方案:
const items = [
{
description: 'first description'
},{
description: 'second description'
},{
description: 'third description'
},{
description: 'fourth description'
},];
function pair(arr,number = 2) {
return arr.reduce(
(acc,cur,i) =>
i % number
? Object.assign([...acc],{
[acc.length - 1]: [...acc[acc.length - 1],cur],})
: [...acc,[cur]],[]
);
}
function Render() {
return <React.Fragment>
{pair(items).map(x => <div className="container">{x.map(y => <div>{y.description}</div>)}</div>)}
</React.Fragment>;
}
ReactDOm.render(
<Render />,document.getElementById("react")
);
.container {
border: 1px solid red;
margin: 10px;
}
<script src="https://cdnjs.cloudFlare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudFlare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>
以上是大佬教程为你收集整理的如何包装由对象数组填充的元素成对全部内容,希望文章能够帮你解决如何包装由对象数组填充的元素成对所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。