我想从其自己的组件中递归添加一个反应组件。我看到了这个例子这是通过子 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>
);
}
});
我收到以下错误消息:
未捕获的类型错误:无法构造“注释”:请使用“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>"
}
]
}
这是 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}/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)