问题
Trying to display a hierarquical tree view with React.js
My render method:
render: function(){
var self= this;
return(
<div className="panel panel-flat content-group-lg">
<div className='panel-body'>
<div className="tree">
<ul>
<li>
<a href="#">Categorias</a>
{ self.printTree(this.state.tree_array) }
</li>
</ul>
</div>
</div>
</div>
)
}
and my printTree method:
printTree: function(level){
console.log(level);
var self = this;
var level_length = level.length;
if(level_length >= 1){
return(
<ul>{
level.map(function(category){
return (
<li key={category.fields.name}>
<a href='#'>{category.fields.name}</a>
</li>
{self.printTree(category.sons_array)}
)
})
}</ul>
)
}
}
The printTree method receives an array that corresponds to a "level" of the tree. My goal is to 'print' each element of this level ( so I use the map to iterate over the array ) but also print any possible sublevels of the current element, so I tried to call the function recursively, passing the 'sons' of the current element as the new array parameter for the recursive call.
For some reason, calling:
{self.printTree(category.sons_array)}
gives me: Uncaught SyntaxError: http://127.0.0.1/gims-webapp/components/NavBar.js: Unexpected token (901:84)
I'm using JSX and can't figure out what JSX is complaining about..
EDIT:
My final structure should look like this:
<div class="tree">
<ul>
<li>
<a href="#">Parent</a>
<ul>
<li>
<a href="#">Child</a>
<ul>
<li>
<a href="#">Grand Child</a>
</li>
</ul>
</li>
<li>
<a href="#">Child</a>
<ul>
<li><a href="#">Grand Child</a></li>
<li>
<a href="#">Grand Child</a>
<ul>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
<li>
<a href="#">Great Grand Child</a>
</li>
</ul>
</li>
<li><a href="#">Grand Child</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
回答1:
JSX requires expects only one Root Node, so this code:
return (
<li key={category.fields.name}>
<a href='#'>{category.fields.name}</a>
</li>
{self.printTree(category.sons_array)}
)
Should be changed to:
return (
<li key={category.fields.name}>
<a href='#'>{category.fields.name}</a>
{self.printTree(category.sons_array)}
</li>
)
Or it's like returning:
<li>
...
</li>
<ul>
...
</ul>
Which are several root nodes.
回答2:
If you paste your code to babel repl, you will see where is error in your example – it is inside level.map(...), because you should return only one react node in map method (but you have <li > + self.printTree there). You can put self.printTree inside this li:
level.map(function(category){
return (
<li key={category.fields.name}>
<a href='#'>{category.fields.name}</a>
{self.printTree(category.sons_array)}
</li>
);
})
来源:https://stackoverflow.com/questions/35797165/react-js-call-recursive-function-in-render