Javascript 如何在 react.js 中递归渲染子组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28205317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:22:06  来源:igfitidea点击:

how to render child components in react.js recursively

javascriptrecursionreactjs

提问by svnm

I wanted to recursively add a react component from within its own component. I saw this example of a tree componentwhich 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.

我想从它自己的组件中递归地添加一个 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>
    );
  }
});

I get the following error message:

我收到以下错误消息:

Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

未捕获的类型错误:无法构造“注释”:请使用“新”运算符,此 DOM 对象构造函数不能作为函数调用。

here is an example of the JSON data passed to the component.

这是传递给组件的 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>"
      }
    ]
}

采纳答案by svnm

If I create the child nodes as an object at the top of the render method, it works fine.

如果我在 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>
    )
  }
}

回答by Francisco Aquino

Here's an alternative in ES6:

这是 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
}

And is some other component:

还有一些其他组件:

<Comments children={post.comments}/>

回答by maimArt

The easiest way is to create a function in the class which returns an instance of your class:

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

RecursiveComponent.rt.js:

递归组件.rt.js:

var RecursiveComponent = React.createClass({
 render: function() {
  // JSX
  ....
 },
 renderRecursive: function(param1)
   return React.createElement(RecursiveComponent, {param1: param1});

});

if you use react-templates library:

如果您使用react-templates 库

RecursiveComponent.rt:

递归组件.rt:

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