如何在React的map循环中每4次迭代插入指定div?
实现每4次迭代后插入清除浮动元素
要在每4个Item组件后插入<div className="clearBoth"></div>,可以在map循环中加入条件判断,每次迭代时根据当前索引决定是否额外返回清除浮动的元素。具体实现如下:
修改后的代码:
{portfolio?.map((portf, index) => { const elements = [ <Item key={`item-${index}`} original={require(`../img/${folder}/${portf.src}`)} thumbnail={require(`../img/${folder}/${portf.src}`)} > {({ ref, open }) => ( <img ref={ref} onClick={open} src={require(`../img/${folder}/${portf.src}`)} className={`associatedMedia${index}`} /> )} </Item> ]; // 每4个元素后插入clearBoth(索引从0开始,第4个元素的index是3,index+1=4) if ((index + 1) % 4 === 0) { elements.push(<div key={`clear-${index}`} className="clearBoth"></div>); } return elements; })}
关键说明
- 条件判断逻辑:用
(index + 1) % 4 === 0来识别每第4个元素的位置(因为数组索引从0开始,第1个元素index为0,第4个为3,index+1刚好是4的倍数)。 - key属性:给每个渲染的元素(包括
Item和clearBoth的div)添加唯一的key,避免React的列表渲染警告。 - 模板字符串优化:把原代码中拼接字符串的写法改成模板字符串,更简洁易读。
内容的提问来源于stack exchange,提问作者Brian Millot
相关产品推荐
相关产品推荐

