Nested comments in Reactjs

帅比萌擦擦* 提交于 2019-12-03 16:43:42

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.

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>
  }
})

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}/>
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!