在嵌套列表

时间:2018-01-05 14:34:29

标签: reactjs recursion react-redux jsx nested-sets

如果我们在ItemsList组件中写下面的内容:

    render(){ 
       return(
          <div>
             <ul>
                {this.props.items.map(item => <Item key={item.id} />)}
             </ul>
          </div>
   )

输出应该是这样的:

<div>
         <ul>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
              <li></li>
          </ul>
</div>

很明显,在Item组件中渲染方法就像

render(){
        return(
            <li>
                **smth here***
            </li>
        )
    }

有没有办法用输出来渲染那种组件:

 <ul>
    <li>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
</ul>

我的意思是:我们有阵列,先拿第一项扫描,然后我们拿另一个项目,扫描后注意它们应该与前一项保持接近(例如),现在我们有结构ul&gt; li * 2然后,在进一步扫描后没有兄弟姐妹,所以我们采取另一个项目并进行相同的扫描,最后我们呈现如上所述的结构。

是的,扫描应该通过数组递归运行并检查一些道具。 在功能下面做我需要的(逻辑上),甚至显示嵌套列表。主要问题是如何以某种方式呈现反应组件

 renderItems(items) {
    //find where to render
    let node = document.getElementById('root');
    node.innerHTML = '';
    if (items.length) {
        var ul = document.createElement('ul');
        var tree = fetchChildElement(ul);
        node.appendChild(tree);
    }
    function fetchChildElement(container, lft, rgt) {
        items.filter(filterItems); //go through data array 
        return container;

        function filterItems(item) {
            //check if item exists in array 
            if (item.Lft === (lft || 0)) {
                var element = document.createElement('li');
                element.innerHTML = (item.Lft + " | " + item.Rgt);

               //check if item got nested items
                if (item.Lft + 1 < item.Rgt) {
                   //if true call recursive function
                   var childContainer = document.createElement('ul');
                   var child = fetchChildElement(childContainer, item.Lft + 1, item.Rgt - 1);
                   element.appendChild(child);
                }

                //add item to array
                container.appendChild(element);

                //check if next element exists and call function for them
                if (rgt && item.Rgt < rgt) {
                   //if true call recursive function
                   fetchChildElement(container, item.Rgt + 1, rgt);
                }
            }
        }
    }
}

我无法理解(并且无法找到)的主要想法是:

  • 有没有办法在不同的<li> s中呈现多个<ul>反应组件?
  • 使用简单的javascript及其appendChild - 没有问题,React可能有其他选择吗?
  • 另外,也许有必要,我使用react-redux,数据来自服务器,正确的渲染应该在我的前端。

任何提示或建议?

修改

我的项目状态如下所示 enter image description here

修改 这是我的js函数的输出,它接受Items数组并只显示leftKey | rightKey(假设它是img1): enter image description here

这是Items的输出(只是通过Item数组映射来渲染每个Item),显示:inline-block只是为了容易看(假设它是img2): enter image description here

最终输出应该是img2上的元素,但是在img1上的层次结构。

在架构下面它应该如何(左侧)以及在树视图(右侧)中更好地理解它

enter image description here

0 个答案:

没有答案
相关问题