Nested comments in Reactjs

后端 未结 2 1987
慢半拍i
慢半拍i 2021-02-10 20:50

I have the following json:

{  
  \"comments\":[  
    {  
      \"id\":1,
      \"comment_text\":\"asdasdadasdsadsadadsa\",
      \"author\":\"adsfasdasdsad\",
          


        
2条回答
  •  伪装坚强ぢ
    2021-02-10 20:59

    This is easier to do with just the one component if you make it responsible for rendering its own children recursively:

    var Comment = React.createClass({
      render() {
        var comment = this.props.comment
        return 
    {comment.children.length > 0 && comment.children.map((child) => { return })}
    } })
    • Live JS Bin example

    If you want to do this without nesting the components so you're just rendering a flat list of s, you can linearise the tree of comments into a list first, e.g.

    function flattenComments(comments, flatComments, level) {
      for (var i = 0, l = comments.length; i < l; i++) {
        var comment = comments[i]
        flatComments.push({comment: comment, level: level})
        if (comment.children.length > 0) {
          flattenComments(comment.children, flatComments, level + 1)
        }
      }
    }
    
    var flatComments = []
    flattenComments(comments, flatComments, 0)
    var renderedComments = flatComments.map((props) => {
      return 
    })
    

提交回复
热议问题