如何递归地呈现react.js中的子组件

时间:2015-01-29 00:58:49

标签: javascript recursion reactjs

我想以递归方式从其自己的组件中添加react组件。我看到了这个tree component的例子,它通过子TreeNodes进行映射并以相同的方式添加子节点。不幸的是,它对我来说根本不起作用。我们的想法是拥有一个简单的注释组件,并且回复将重用相同的组件。

var Comment = React.createClass({
  render: function() {    
    return (
        <div className="comment">

          {/* text and author */}
          <div className="comment-text">
            <span className="author">{this.props.author}</span>         
            <span className="body" dangerouslySetInnerHTML={{__html: this.props.body}} />
          </div>

          {/* replies */}
          <div className="replies">
           {
             this.props.replies.map(function(reply) {
               <Comment body={reply.body} author={reply.author} />
             }.bind(this))
          }
          </div>

      </div>
    );
  }
});

我收到以下错误消息:

未捕获的TypeError:无法构建&#39;评论&#39;:请使用&#39; new&#39;运算符,此DOM对象构造函数不能作为函数调用。

这是传递给组件的JSON数据的示例。

{ "author" : "Some user",
  "body" : "<div>Great work</div>",
  "replies" : [ { "author" : "A user replying",
        "body" : "<div Yes it was great work</div>"
      },
      { "author" : "Another user replying",
        "body" : "<div It really was great work!</div>"
      }
    ]
}

3 个答案:

答案 0 :(得分:34)

这是ES6中的另一种选择:

import React, { Component, PropTypes } from 'react'

export default class Comments extends Component {

  render() {

    const { children } = this.props

    return (
      <div className="comments">
        {children.map(comment =>
          <div key={comment.id} className="comment">
            <span>{comment.content}</span>
            {comment.children && <Comments children={comment.children}/>}
          </div>
        )}
      </div>
    )

  }

}

Comments.propTypes = {
  children: PropTypes.array.isRequired
}

还有其他一些组成部分:

<Comments children={post.comments}/>

答案 1 :(得分:14)

如果我在渲染方法的顶部创建子节点作为对象,它可以正常工作。

export default class extends React.Component {
  let replies = null
  if(this.props.replies){
    replies = this.props.replies.map((reply) => {
      return (
        <Comment author={reply.author} body={reply.body} />
      )
    })
  }

  render() {
    return (
      <div className="comment">
        <div className="replies">{ replies }</div>
      </div>
    )
  }
}

答案 2 :(得分:1)

最简单的方法是在类中创建一个返回类实例的函数:

<强> RecursiveComponent.rt.js:

<div>
  ...
  <div rt-repeat="recursiveChild in this.props.recursiveItem.recursiveChilds">
            {this.renderRecursive(recursiveChild)}
  </div>
</div>

如果您使用react-templates library

<强> RecursiveComponent.rt:

$('.slidetpl img[src=""]').hide();