我试图在React中构建一个TreeView组件并执行以下操作。
import React from 'react';
/* components */
import {TreeNode} from './TreeNodeComponent';
export const TreeView = React.createClass({
getInitialState(){
return {
parent: [
{
text: "Parent",
children:[
{
text: 'Child',
children: [
{
text: 'Grandchild',
children: [
{ text: Date() },
{ text: Date() },
]
}
]
}
]
}
]
}
},
render(){
let parents = this.state.parent;
let nodes = advertisers.map( (n, i)=>{
return <TreeNode key={i} node={n} children={n.children} />
});
return(
<ul>
{nodes}
</ul>
)
}
})
然后TreeNode组件类似于以下
import React from 'react';
export const TreeNode = React.createClass ({
render(){
let nodes = this.props.children.map( (n, i)=>{
let element = n.children ? <TreeNode key={i} node={n} children={n.children} /> : <TreeNode key={i} node={n} children={[]} />
return element
});
return(
<span>
<li>{this.props.node.text}</li>
<ul>{nodes}</ul>
</span>
)
}
})
如果下一个没有任何孩子,我将一个空数组传递给子道具。但这会产生一个空的UL(应该如此) - 有更好的方法吗?我是否应该在对儿童道具施加压力之前进行检查?