基于深度数据渲染嵌套列表



在React中,我如何呈现以下数据

const headings: [
{depth: 2, value: "Ayyy"}
{depth: 2, value: "Beee"}
{depth: 3, value: "Beee One"}
{depth: 3, value: "Beee Two"}
{depth: 3, value: "Beee Three"}
{depth: 2, value: "Ceee"}
];

转换为以下HTML?

<ol>
<li>Ayyy</li>
<li>
Beee
<ol>
<li>Beee One</li>
<li>Beee Two</li>
<li>Beee Three</li>
</ol>
</li>
<li>Ceee</li>
</ol>

我的尝试:

const TableOfContents = ({ headings }) => (
<ol>
{headings.map(heading => {
// Depth 2
if (heading.depth === 2) {
return (
<li>
{heading.value}
</li>
)
}
// Depth 3
else if (heading.depth === 3) {
// Depth 3 ???
// If depth === 3 and previousDepth === 2, render <ol><li>{heading.value}</li>
// If depth === 3 and previousDepth === 3, render <li>{heading.value}</li>  
// If depth === 3 and nextDepth === 2, render <li>{heading.value}</li></ol>
}
})}
</ol>
);

您可以首先这样更改数据结构:

const headings: [
{depth: 2, value: "Ayyy"},
{depth: 2, value: "Beee", children: [
{depth: 3, value: "Beee One"}
{depth: 3, value: "Beee Two"}
{depth: 3, value: "Beee Three"}
]},
{depth: 2, value: "Ceee"}
];

您可以编写如下jsx渲染函数:

const TableOfContents = ({ headings }) => (
<ol>
{headings.map(heading => {
return (
<li>
{heading.value}
if (heading.children) {
<ol>
heading.children.map(child => <li>{child.value}</li>
</ol>
}
</li>
)
})}
</ol>
);

希望能有所帮助。

您需要另一个值,它是项的父级。您必须定义项的父项,以便嵌套它。

最新更新