问题
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.
回答1:
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
回答2:
Fixed:
renderRecursive(level, nodes){
return nodes.map(node => {
return (
<div>
<div>{node.label}</div>
{(node.type === 'CATEGORY' && node.nodes) && this.renderRecursive(level++, node.nodes)}
</div>)
});
};
回答3:
Okay this is a fun little one, but your issue is that you aren't actually looking at it the right way and as a result aren't building your markup structure correctly :P
By the looks of your Fiddle your end result actually want's to be this:
<div>
<div>
Category 1
<div>
Subcategory 1
<div>
Privilege 11
</div>
</div>
</div>
<div>
Category 2
<div>
Subcategory 2
<div>
Privilege 21
</div>
<div>
Privilege 22
</div>
</div>
</div>
</div>
Boy that was annoying to type... Anyways, so once you look at this you can see:
- A parent div
- Every child is wrapped in a div, and has the label and (potentially) a child.
So now we build:
... or not because you answered it XD
来源:https://stackoverflow.com/questions/52510043/recursive-rendering-of-components-at-all-levels