Render recursively a nested data in React

匿名 (未验证) 提交于 2019-12-03 01:27:01

问题:

How would i go about rendering a menu with nested

    items with an an unknown amount of children in react from an object like in the following example?

    [   {     title: "Top level 1",     slug: "top-level-1",     children: [       {         title: "Sub level 1",         slug: "sub-level-1",         children: [           {             title: "Sub Sub Level 1"             slug: "sub-sub-level-1"           }         ]       }       {         title: "Sub level 2",         slug: "sub-level-2"       }     ]   },   {     title: "Top level 2",     slug: "top-level 2"   } ] 

    回答1:

    Codesandbox example

    You just have to recursively call Menu component for its children to display and pass as a data prop.

    let data = [   {     title: "Top level 1",     slug: "top-level-1",     children: [       {         title: "Sub level 1",         slug: "sub-level-1",         children: [           {             title: "Sub Sub Level 1",             slug: "sub-sub-level-1",             children: [               {                 title: "Sub Sub Level 2",                 slug: "sub-sub-level-2"               }             ]           }         ]       },       {         title: "Sub level 2",         slug: "sub-level-2"       }     ]   },   {     title: "Top level 2",     slug: "top-level 2"   } ];  const Menu = ({data}) => {   return (     
      {data.map(m => { return (
    • {m.title} {m.children && }
    • ); })}
    ); } const App = () => (

    Start editing to see some magic happen {'\u2728'}

    );


    回答2:

    You could recursively Render the component for nested data which has variable depth.

    Sample Snippet.

    var data = [   {     title: "Top level 1",     slug: "top-level-1",     children: [       {         title: "Sub level 1",         slug: "sub-level-1",         children: [           {             title: "Sub Sub Level 1",             slug: "sub-sub-level-1"           }         ]       },       {         title: "Sub level 2",         slug: "sub-level-2"       }     ]   },   {     title: "Top level 2",     slug: "top-level 2"   } ]  const MyComponent  = (props) => {      if(Array.isArray(props.collection)) {          return 
      {props.collection.map((data)=> { return
      • {data.title}
      • {data.slug}
    • }) }
    } return null; } class App extends React.Component { render() { return ( ) } } ReactDOM.render(, document.getElementById('app'))
      

    P.S. The snippet contains formatting errors, but I am sure you will be able to rectify that. Snippet was to give an idea of the approach



    标签
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!