Can a React prop type be defined recursively?

后端 未结 3 1549
萌比男神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:10

    A React prop type is just a function, so it can be referenced lazily like this:

    function lazyFunction(f) {
        return function () {
            return f.apply(this, arguments);
        };
    }
    
    var lazyTreeType = lazyFunction(function () { 
        return treeType;
    });
    
    var treeType = React.PropTypes.shape({
        value: React.PropTypes.string.isRequired,
        children: React.PropTypes.arrayOf(lazyTreeType)
    })
    

    The rest of the code for a complete working example (also available as a jsfiddle):

    function hasChildren(tree) {
        return !!(tree.children && tree.children.length);
    }
    
    var Tree = React.createClass({
        propTypes: {
            tree: treeType
        },
        render: function () {
            return this.renderForest([this.props.tree], '');
        },
        renderTree: function (tree, key) {
            return 
  • {tree.value}
    {hasChildren(tree) && this.renderForest(tree.children, key)}
  • ; }, renderForest: function (trees, key) { return
      {trees.map(function (tree) { return this.renderTree(tree, key + ' | ' + tree.value); }.bind(this))}
    ; } }); var treeOfLife = { value: "Life", children: [ {value: "Animal", children: [ {value: "Dog"}, {value: "Cat"} ]}, {value: "Plant"} ]}; React.render( , document.getElementById('tree'));

    Screenshot of the result:

    Screenshot of the result

提交回复
热议问题