这是对象的接口,目标数据是这个对象的数组,所以
looks like;
export interface IMenuModel {
Id: number
itemName: string;
parentId?: number;
childItems: IMenuModel[];
}
示例内容示例;
[ {itemName:"League",.. childItems: [{itemName:"Fixture",.. childitems:[...]]}] } ]
这是我要创建的示例列表;
<li className="dropdown">
<a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">League<span className="caret" /></a>
<ul className="dropdown-menu" role="menu">
<li><a href="#">Fixture</a>
<ul className="dropdown-menu" role="menu">
<li>
<a href="#">item name</a>
</li>
<li>
<a href="#">item name</a>
</li>
</ul>
</li>
</ul>
</li>
这是我试图做的,但只能深入一个;
listLoop(items:IMenuModel[]):JSX.Element[] {
var menuJsx:JSX.Element[] = items.map((item)=>{
return (<li key={item.Id} className="dropdown">
<a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> {item.itemName}<span className="caret" /></a>
</li>);
})
return menuJsx;
}
如何创建递归函数来实现这一目标?
答案 0 :(得分:2)
像这样写:
_createList(item){
return item.map((el,i)=>{
return <div key={i}>
{el.name}
{el.child.length ? this._createList(el.child) : null}
</div>
})
}
render() {
return (
<div >
{this._createList(item)}
</div>
)
}
检查工作jsfiddle
:https://jsfiddle.net/mayankshukla5031/wxrc24o1/
var item=[
{
name: '1',
child: []
},
{
name: '2',
child: [
{
name: '2.1',
child: [
{
name: '2.1.1',
child:[
{
name: '2.1.1.1',
child: [],
}
]
}
]
},
{
name: '2.2',
child: []
}
]
}
];
class App extends React.Component {
constructor() {
super();
}
_createList(item){
return item.map((el,i)=>{
return <div key={i}>
{el.name}
{el.child.length ? this._createList(el.child) : null}
</div>
})
}
render() {
return (
<div >
{this._createList(item)}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"/>
答案 1 :(得分:0)
如果listLoop
不为空,请向[{1}}添加递归调用:
item.childItems