React中如何正确循环渲染返回嵌套div结构
代码错误点说明
你的代码存在几个核心问题,导致无法渲染出预期的嵌套DOM结构:
- 语法错误:样式对象声明缺少赋值等号,且使用了不存在的CSS属性
borderSize(React内联样式对应边框宽度的合法驼峰属性为borderWidth) - 逻辑错误:内层循环生成的子div没有作为children放入外层父div内部,而是通过
push/unshift和父div平级堆在同一个数组里,完全没有嵌套关系 - 变量未定义:没有初始化存储元素的
fooStyle数组,直接调用数组方法会抛出引用错误 - 性能问题:固定不变的样式对象写在循环内部,每次循环都会重复创建相同对象,造成不必要的开销
- 规范问题:循环生成的React元素没有添加唯一
key属性,会触发React渲染警告
修正后的实现代码
核心思路是外层循环每生成一个父div前,先收集好当前父div需要包裹的所有子div,再将子div作为父元素的子节点传入,最终收集所有父节点返回即可。
以下是对应你给出的示例DOM结构的实现:
const nestedDivs = () => { // 配置每个外层父div包含的子div数量,对应示例中第一个父div2个子元素、第二个3个子元素的结构 const childCountPerParent = [2, 3]; const parentContainer = []; // 固定样式移到循环外,只声明一次 const parentStyle = { borderColor: '#fff', borderWidth: '1px', borderStyle: 'solid', background: '#ff0000', }; const childStyle = { borderColor: '#fff', borderWidth: '1px', borderStyle: 'solid', background: '#ffcc00', }; for (let parentIndex = 0; parentIndex < childCountPerParent.length; parentIndex++) { const currentChildCount = childCountPerParent[parentIndex]; const childElements = []; // 生成当前父节点下的所有子节点 for (let childIndex = 0; childIndex < currentChildCount; childIndex++) { childElements.push( <div style={childStyle} key={`child-${parentIndex}-${childIndex}`}></div> ); } // 将子节点作为父节点的内容,存入外层容器 parentContainer.push( <div style={parentStyle} key={`parent-${parentIndex}`}> {childElements} </div> ); } // React 16及以上版本支持直接返回元素数组 return parentContainer; }
补充说明
- 如果你需要动态生成不同数量的父div、每个父div对应不同数量的子div,只需要修改
childCountPerParent数组的配置即可,比如传入[1,4,2]就会生成3个父div,分别包含1、4、2个子div - 不要使用
unshift往数组头部插入元素,会导致最终渲染的元素顺序和预期相反 - 如果你使用的React版本低于16,需要把返回的数组包裹在一个空的Fragment标签
<React.Fragment>{parentContainer}</React.Fragment>里再返回
内容的提问来源于stack exchange,提问作者aBogdan
相关产品推荐
相关产品推荐

