2017-08-10 120 views
0

如何使用React渲染遞歸列表?比方說你有一個像遞歸渲染組件

{ 
    "list": [ 
     "Parent", 
     "subList": [ 
      { 
       "First Child", 
       "subList": [ 
        { 
         "Grand Child 1-1" 
        }, 
        { 
         "Grand Child 1-2" 
        } 
       ] 
      }, 
      { 
       "Second Child", 
       "subList": [ 
        { 
         "Grand Child 2-1", 
         "sublist": [] 
        } 
       ] 
      } 
     ] 
    ] 
} 

你會如何寫一個遞歸地圖功能來呈現縮進子列表清單數據?以下是我的嘗試,但我想遞歸。

renderCheckboxRows = (list) => { 
    list.map((filter, index) => { 

     let content = <FilterRow key={index} {...filter} />; 
     let subListContent = []; 

     if (filter.subList && filter.subList.length > 0) { 
      filter.subList.map((filter, index) => { 
       subListContent.push(<FilterRow key={index} {...filter} />); 
      }); 
     } 
     return (content + subListContent); 
    }); 

} 

回答

1

我通常通過引入一個專用的部件,爲此目的做。

讓我們將它命名爲Node。它的使用將是如下:

<Node caption={root.caption} children={root.children}/> 

內。然後Node.render

render() 
{ 
    var children = []; 

    children = this.props.children.map((c) => 
    { 
     return <Node caption={c.caption} children={c.children}> 
    }); 

    return (
     <div> 
      <div>{this.props.caption}</div> 
      {children} 
     </div> 
    ); 
} 

這只是一個例子草案,而不是divs你將有自己的組件,但它描述了一個思路。