各级组件的递归渲染 [英] Recursive rendering of components at all levels

查看:37
本文介绍了各级组件的递归渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助来递归渲染所有级别的组件.顶层有节点,然后遵循相同的结构直到最后.如果我们获得 Privilege,我们会以不同的方式呈现它,但是所有类别都需要显示在上面.

请在这里找到小提琴:https://jsfiddle.net/vedvrat13/dq0u2pm7/

预期输出:

--类别 1----子类别1------特权11--第2类----子类别2------特权21------特权22

请帮我做同样的事情.我尝试了多种方法,但是我对如何渲染和调用函数也很困惑.

解决方案

这可能会帮助您形成您所期望的结构.您需要形成树结构来实现它并在这里找到工作模块 https://stackblitz.com/edit/react-65krxc?file=TreeComponent.js

renderRecursiveNodes(nodes){返回 nodes.map(node => {返回 (<div><TreeComponent node={node}/></div>)});};使成为() {返回 (<div>{this.renderRecursiveNodes(this.state.items)}

)}

在你的 TreeComponent 内部

render() {让子节点;如果 (this.props.node.nodes && this.props.node.nodes.length > 0) {console.log('test');childNodes = this.props.node.nodes.map(function(node, index) {return <li key={index}><TreeComponent node={node}/></li>});}返回 (<div><h5>{this.props.node.label}<ul >{子节点}

)}

如果您需要更多信息,请告诉我.谢谢

I need help in to recursively render the components at all levels. There are Nodes at top level and then the same structure is followed till the end. If we get Privilege we render it differently however all Categories need to be displayed above.

Please find a fiddle here: https://jsfiddle.net/vedvrat13/dq0u2pm7/

Expected Output:

--Category 1
----SubCategory 1
------Privilege 11

--Category 2
----SubCategory 2
------Privilege 21
------Privilege 22

Please help me with the same. I tried multiple approaches however i am getting stuck as to how to render and call the function too.

解决方案

This might help you to form the structure what you are expecting. You need to form tree structure to achieve it and find the working module here https://stackblitz.com/edit/react-65krxc?file=TreeComponent.js

renderRecursiveNodes(nodes){
    return nodes.map(node => {
            return (
            <div>
              <TreeComponent node={node} />
          </div>)
    });
};

  render() {
    return (
      <div>
          {this.renderRecursiveNodes(this.state.items)}      
      </div>      
    )
  }

Inside your TreeComponent

render() {
    let childNodes;

    if (this.props.node.nodes && this.props.node.nodes.length > 0) {
      console.log('test');
      childNodes = this.props.node.nodes.map(function(node, index) {
        return <li key={index}><TreeComponent node={node} /></li>
      });
    }

    return (
     <div>
        <h5>
          {this.props.node.label}
        </h5>
        <ul >
          {childNodes}
        </ul>
      </div>
    )
  }

Please let me know if you need more info. Thanks

这篇关于各级组件的递归渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆