基于嵌套数组渲染嵌套元素 [英] Render a Nested Element based on nested Array
问题描述
我得到了这个嵌套数组,我需要遍历它来创建嵌套容器. lvl4
应该放在lvl3
内,lvl3
到lvl2
内,并且lvl2
放在lvl1
内.
I got this nested arrays and I need to loop through it to create nested containers. lvl4
should go inside lvl3
, lvl3
to lvl2
and lvl2
inside lvl1
.
const elements = [
{ name: 'a-lvl1', innerEl: [
{ name: 'a1-lvl2', innerEl: [
{ name: 'a1-lvl3' , innerEl: [
{ name: 'a-lvl4', innerEl: [] }
] },
{ name: 'a2-lvl3' , innerEl: [
{ name: 'a-lvl4', innerEl: [] }
] }
] },
{ name: 'a2-lvl2', innerEl: [
{ name: 'a-lvl3' , innerEl: [
{ name: 'a-lvl4', innerEl: [] }
] }
] },
{ name: 'a3-lvl2', innerEl: [
{ name: 'a-lvl3' , innerEl: [
{ name: 'a-lvl4', innerEl: [] }
] }
] },
] },
{ name: 'b-lvl1', innerEl: [ { }] },
{ name: 'c-lvl1', innerEl: [ { }] }
]
这是当前的脚本,正在运行,但是我正在寻找更简单的解决方案.
This is the current script, which is working but I'm looking for a much simpler solution.
let renderElements = null;
if( elements !== undefined || elements.length != 0 ) {
renderElements = elements.map( lvl1 => {
let lvl2Blocks = null;
if( lvl1.innerEl !== undefined || lvl1.innerEl.length != 0) {
lvl2Blocks = lvl1.innerEl.map( lvl2 => {
let lvl3Blocks = null;
if( lvl2.innerEl !== undefined || lvl2.innerEl.length != 0) {
lvl3Blocks = lvl2.innerEl.map( lvl3 => {
let lvl4Blocks = null;
lvl4Blocks = lvl3.innerEl.map( lvl4 => {
return (
<div name={lvl4.name} selected={null} >
{ lvl4.innerEl !== undefined && lvl4Blocks }
</div>
)
});
return (
<div name={lvl3.name} selected={null} >
{ lvl3.innerEl !== undefined && lvl4Blocks }
</div>
)
});
}
return (
<div name={lvl2.name} selected={null} >
{ lvl2.innerEl !== undefined && lvl3Blocks }
</div>
)
});
}
return (
<div name={lvl1.name} selected={null} >
{ lvl1.innerEl !== undefined && lvl2Blocks }
</div>
)
});
}
有什么想法吗?谢谢.
Any ideas? Thanks.
推荐答案
如已显示代码框
同样,窍门是在这里使用递归.因此,使用这个简单的组件,您将能够根据需要进行深度渲染.
Again, the trick is to use recursion here. So with this simple component you will be able to render as deep as you wish.
function ListItem({ item }) {
let children = null;
if (item.innerEl && item.innerEl.length) {
children = (
<ul>
{item.innerEl.map(i => (
<ListItem item={i} key={i.id} />
))}
</ul>
);
}
return (
<li>
{item.name}
{children}
</li>
);
}
但是请记住,您需要修复数据结构.如果您的数组应该为空,则不要在其中放置一个空对象:
But keep in mind that you need to fix your datastructure. If your array is supposed to be empty, don't put an empty object in it like that:
{ name: 'b-lvl1', innerEl: [ { }] },
这应该看起来像这样,或者您需要修改ListItem
组件以检查第一项是否为空对象
This should look like this, or you need to modify the ListItem
component to check if the first item is an empty object
{ name: 'b-lvl1', innerEl: [] },
这篇关于基于嵌套数组渲染嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!