如何递归地呈现react.js中的子组件 [英] how to render child components in react.js recursively
问题描述
我想以递归方式从其自己的组件中添加react组件。我看到了一个树组件,它通过子TreeNodes进行映射并以相同的方式添加子节点。不幸的是,它对我来说根本不起作用。想法是有一个简单的注释组件,回复将重用相同的组件。
I wanted to recursively add a react component from within its own component. I saw this example of a tree component which was mapping through the child TreeNodes and adding child nodes in the same way. Unfortunately it doesn't work at all for me. The idea was to have a simple comment component, and the replies would reuse the same component.
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:无法构造'Comment':请使用'new'运算符,此DOM对象构造函数不能作为函数调用。
这里是传递给组件的JSON数据的一个示例。
here is an example of the JSON data passed to the component.
{ "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>"
}
]
}
推荐答案
如果我在渲染方法的顶部创建子节点作为对象,它可以正常工作。
If I create the child nodes as an object at the top of the render method, it works fine.
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>
)
}
}
这篇关于如何递归地呈现react.js中的子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!