reactjs 我想在React Js中将父子关系中的嵌套对象数组呈现为树

new9mtju  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(112)

我想在reactJS中将这个对象数组呈现为一个可展开的树。在节点上展开以显示单击时的子节点。
下面的数据只是一个非常嵌套的数组的片段。

const familiy =[
{
  //
  "data": {"id":"John", "age": 90},
  "children": [
    {
      "data": {"id":"Mary", "age": 60},
      "children": [
        {"data": {"id":"Mercy", "age": 45}} 
      ]
    },
    {
      "data": {"id":"Paul", "age": 60}
    },
    {
      "data": {"id":"Dolores", "age": 55}
    },
  ],
};
]

[The result should look something like this][1]

  [1]: https://i.stack.imgur.com/4frB0.png
scyqe7ek

scyqe7ek1#

您可以使用类似于以下内容的内容:

class App extends React.Component {
    render() {
const familiy = [
    {
      data: { id: "John", age: 90 },
      children: [
        {
          data: { id: "Mary", age: 60 },
          children: [{ data: { id: "Mercy", age: 45 } }],
        },
        {
          data: { id: "Paul", age: 60 },
        },
        {
          data: { id: "Dolores", age: 55 },
        },
      ],
    }
  ];

  const renderChildren = (v) => {
    return (
      <li key={v.data.id}>
        {v.data.id}, Age: {v.data.age}
        <ul>
          {v.children &&
            v.children.map((v2) => {
              return renderChildren(v2);
            })}
        </ul>
      </li>
    );
  };

  return (
    <div>
      <h1>Parent Child Tree</h1>
      <div>Render nested array of objects of parent-child relationship as a tree</div>
      <ul>
            {familiy.map((v) => {
              return renderChildren(v);
            })}
          </ul>
    </div>
  );
    }
}

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

相关问题