Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - Can a React prop type be defined recursively?

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

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

Here's a definition of treeType that obviously doesn't work but hopefully illustrates what I'm trying to express.

var treeType = React.PropTypes.shape({
    value: React.PropTypes.string,
    children: React.PropTypes.arrayOf(treeType)
})

Is there a way to let the type refer to itself lazily so this can work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 <li className="tree" key={key}>
            <div title={key}>{tree.value}</div>
            {hasChildren(tree) &&
                this.renderForest(tree.children, key)}
        </li>;
    },
    renderForest: function (trees, key) {
        return <ol>{trees.map(function (tree) {
            return this.renderTree(tree, key + ' | ' + tree.value);
        }.bind(this))}</ol>;
    }
});

var treeOfLife = { value: "Life", children: [
    {value: "Animal", children: [
        {value: "Dog"},
        {value: "Cat"}
    ]},
    {value: "Plant"}
]};

React.render(
    <Tree tree={treeOfLife}/>,
    document.getElementById('tree'));

Screenshot of the result:

Screenshot of the result


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...