You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:25:23