Nested comments in Reactjs

后端 未结 2 1992
慢半拍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 <div>
          <div dangerouslySetInnerHTML={{__html: comment.comment_text}}/>
          {comment.children.length > 0 && comment.children.map((child) => {
            return <Comment key={child.id} comment={child}/>
          })}
        </div>
      }
    })
    
    • Live JS Bin example

    If you want to do this without nesting the components so you're just rendering a flat list of <Comment>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 <Comment {...props}/>
    })
    
    0 讨论(0)
  • 2021-02-10 21:03

    You need two components: Comments and Comment.

    Comment = React.createClass({
      render: function(){
        var comment = this.props.comment;
        return <div>
          <p>{comment.author} says {comment.comment_text}</p>
          <Comments comments={comment.children} />
        </div>
      }
    });
    
    Comments = React.createClass({
      render: function(){
        return <div>
          {this.props.comments.map(function(comment){
            return <Comment key={comment.id} comment={comment} />
          })
        </div>
      }
    });
    

    The Comment renders Comments, which in turn can render Comment nodes, etc. This recursively builds the comment structure.

    0 讨论(0)
提交回复
热议问题