如何在 React.js 递归地渲染子组件
how to render child components in react.js recursively
我想从它自己的组件中递归添加一个反应组件。我看到了这个树组件的示例,它通过子 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>
);
}
});
我收到以下错误消息:
未捕获的类型错误:无法构造"注释":请使用"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}/>
如果我在 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>
)
}
}
最简单的方法是在类中创建一个函数,该函数返回类的实例:
RecursiveComponent.rt.js:
var RecursiveComponent = React.createClass({
render: function() {
// JSX
....
},
renderRecursive: function(param1)
return React.createElement(RecursiveComponent, {param1: param1});
});
如果你使用 反应模板库:
RecursiveComponent.rt:
<div>
...
<div rt-repeat="recursiveChild in this.props.recursiveItem.recursiveChilds">
{this.renderRecursive(recursiveChild)}
</div>
</div>
相关文章:
- 数组在递归方法中设置为null
- Kendo:我该如何在树视图中创建一个递归的hieiarchy
- 递归使用 eval() 是检查程序执行的好方法吗?
- 使用递归、Ramda.js和无点样式重构字符串的getPermutations()
- 递归深度比较
- Eloquent JavaScript递归示例如何终止为返回1,但仍然输出指数值
- 递归函数中断
- 如何递归地获取嵌套对象中所有子对象的列表
- JavaScript 素数搜索无限递归
- 在递归生成器函数中,yield后面的*(星号/星号)语法意味着什么
- 递归|两个函数名
- 有没有一种方法可以在Javascript中进行可变递归currying
- 如何在 React.js 递归地渲染子组件
- React 应该组件更新太多的递归
- 如何在 RivetsJS 中处理递归嵌套组件
- 在递归聚合物组件中插入新子组件时,无法读取未定义的属性“concat”
- React 不会渲染递归反应式组件
- 用递归数组加载递归组件
- 类似python的javascript中URI组件的递归解码
- 递归的 Qml 组件