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

如何实现可将React元素循环渲染指定次数的Looper组件

Looper 组件优化实现

核心调整是将外部传入的冗余数组参数替换为数值类型的times参数,由组件内部生成对应长度的遍历源,无需额外定义虚拟数组。

优化后组件代码

import React from 'react'

function Looper({ children, times, needItemWrapper = false }) {
  // 内部生成指定长度的数组作为遍历源
  return (
    <>
      {Array.from({ length: times }, (_, index) => (
        <React.Fragment key={index}>
          {/* needItemWrapper参数控制是否要给每个子元素额外套div,不需要可以直接返回children */}
          {needItemWrapper ? <div>{children}</div> : children}
        </React.Fragment>
      ))}
    </>
  )
}

使用方式

直接传入渲染次数即可,无需定义冗余数组:

<Looper times={5}>
  <span>Hello Guys..</span>
</Looper>

可选扩展点

如果需要给子元素传递当前循环的索引值,可以修改组件为渲染回调的形式,适用场景更灵活:

function Looper({ children, times }) {
  return (
    <>
      {Array.from({ length: times }, (_, index) => (
        <React.Fragment key={index}>
          {/* 支持直接传子元素或者传回调函数拿索引 */}
          {typeof children === 'function' ? children(index) : children}
        </React.Fragment>
      ))}
    </>
  )
}

// 带索引的使用示例
<Looper times={5}>
  {(index) => <span>第 {index + 1} 行:Hello Guys..</span>}
</Looper>

内容的提问来源于stack exchange,提问作者Code Lover

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:24:05