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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…