Can a React prop type be defined recursively?

后端 未结 3 1545
萌比男神i
萌比男神i 2020-12-16 14:25

Suppose we\'re defining a React class that will display a tree.

React.createClass({
    propTypes: {
        tree: treeType
    },
    render: function () {
         


        
3条回答
  •  离开以前
    2020-12-16 15:01

    Here's another approach, courtesy of jethrolarson on GitHub:

    Given the recursive component Tree

    import React from 'react';
    
    const Tree = ({treeData}) => (
        
    {treeData.nodeName}{' '} {treeData.children.map(subTree => ( ))}
    );

    that takes a tree data structure like the one below

                    Root
                    /  \
               Child1   Child2
              /     \        \
         GChild1   GChild2   GChild3
    

    (as code:

    const treeData = {
        nodeName: "Root",
        children: [
            {
                nodeName: "Child1",
                children: [
                    {nodeName: "GChild1"},
                    {nodeName: "GChild2"},
                ]
            },
            {
                nodeName: "Child2",
                children: [
                    {nodeName: "GChild3"},
                ]
            },
        ]
    };
    

    ),

    the propTypes for Tree can be defined as:

    import PropTypes from 'prop-types';
    
    const treeDataShape = {
        nodeName: PropTypes.string.isRequired,
    };
    treeDataShape.children = PropTypes.arrayOf(PropTypes.shape(treeDataShape));
    
    Tree.propTypes = {
        treeData: PropTypes.shape(treeDataShape),
    };
    

    Note how all of the references to treeDataShape refer to the same object. Defining children after the object is created lets you recursively reference the same object.

提交回复
热议问题