我想从自己的组件中递归添加一个react组件。我看到了一个树组件的示例,该组件通过子TreeNode进行映射并以相同方式添加子节点。不幸的是,这对我根本不起作用。这个想法是要有一个简单的注释组件,而答复将重用相同的组件。
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:无法构造“注释”:请使用“ new”运算符,此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>" } ] }
如果我在render方法的顶部将子节点创建为一个对象,则可以正常工作。
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> ) } }