我期待採取以下JSON:如何創建嵌套李-UL-li元素
{
"comments":[
{
"id":3,
"comment":"asdasdasdasdsadsaasd",
"author":"Adam",
"post_id":126,
"ancestry":null,
"created_at":"2014-06-18T00:25:04.421Z",
"updated_at":"2014-06-18T00:25:04.421Z",
"children":[
{
"id":4,
"comment":"asdasdasdasdsadsaasd",
"author":"Adam",
"post_id":126,
"ancestry":"3",
"created_at":"2014-06-18T00:25:57.913Z",
"updated_at":"2014-06-18T00:25:57.913Z",
"children":[
{
"id":7,
"comment":"asdasdasdasdsadsaasd",
"author":"Adam",
"post_id":126,
"ancestry":"3/4",
"created_at":"2014-06-18T00:57:36.277Z",
"updated_at":"2014-06-18T00:57:36.277Z",
"children":[
]
},
{
"id":5,
"comment":"asdasdasdasdsadsaasd",
"author":"Adam",
"post_id":126,
"ancestry":"3/4",
"created_at":"2014-06-18T00:26:12.017Z",
"updated_at":"2014-06-18T00:26:12.017Z",
"children":[
]
}
]
}
]
}
]
}
這可能會對許多嵌套更多的孩子或意見,你看,寫一個遞歸函數做兩件事情:
走過每個評論博客尋找
children
,從那裏通過那些走 - 重複,直到它自己的死衚衕(該功能應該是遞歸的 - 看看我有這麼遠低於)對於
children
每個孩子及其相關子等等等等,這些元素應該有一個類的nested
,然後讓我做這樣的事情:.nested .nested .nested .nested {/ * CSS規則在這裏爲4個級別的嵌套*的/}
基本上我應該能夠通過ul
複製這種形式的嵌套的和li
的
我有什麼?
我建立了一個反應成分混入該執行以下操作:
/**
* Helps with abstracting certian logic from the comments component.
*/
var CommentsMixins = {
commentElements: [],
/**
* Recursive fucntion to help get all nested comments.
*
* Keeps the order of the nested comments And renders a react component
* which is a single comment.
*/
renderComments: function(comments) {
for (var key in comments) {
if (key === 'children' && key.length !== 0) {
var nestedComments = comments[key]
for (var i = 0; i < nestedComments.length; i++) {
this.commentElements.push('<li id="comment-'+nestedComments[i].id+'" class="indented"> <h1>'+nestedComments[i].author+' <small>said ... </small></h1> <p>'+nestedComments[i].comment+'</p></li>');
this.renderComments(nestedComments[i]);
}
}
},
getCommentElements: function() {
return this.commentElements;
}
}
這反過來會吐出:
<ul>
<li> ... </li> <!-- id: 3 -->
<li> ... </li> <!-- id: 4 -->
<li> ... </li> <!-- id: 7 -->
<li> ... </li> <!-- id: 5 -->
...
</ul>
當它應該是這樣的:
<ul>
<li> <!-- id: 3 -->
<ul>
<li> ... </li> <!-- id: 4 -->
</ul>
</li>
...
<ul>
我需要改變我的遞歸函數來獲得這種類型的內容T' (注意:你可以假設父ul
已經完成渲染的所有li
的和他們的孩子和孫子等等等等都呈現最外層<ul></ul>
內。)
@ user2864740你能舉個例子嗎? – user3379926