how to render child components in react.js recursively

前端 未结 3 1170
渐次进展
渐次进展 2020-12-07 22:46

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

相关标签:
3条回答
  • 2020-12-07 23:36

    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>
        )
      }
    }
    
    0 讨论(0)
  • 2020-12-07 23:38

    Here's an alternative in 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}/>
    
    0 讨论(0)
  • 2020-12-07 23:39

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

    RecursiveComponent.rt.js:

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

    if you use react-templates library:

    RecursiveComponent.rt:

    <div>
      ...
      <div rt-repeat="recursiveChild in this.props.recursiveItem.recursiveChilds">
                {this.renderRecursive(recursiveChild)}
      </div>
    </div>
    
    0 讨论(0)
提交回复
热议问题