根据深度数据渲染嵌套列表

时间:2020-07-09 19:29:37

标签: reactjs jsx

在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>
);

2 个答案:

答案 0 :(得分:1)

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

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>
);

希望有帮助。

答案 1 :(得分:0)

您将需要另一个值,该值是项目的父项。您必须定义该项目的父项才能嵌套。