可以递归地定义React prop类型吗? [英] Can a React prop type be defined recursively?
本文介绍了可以递归地定义React prop类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们正在定义一个将显示树的React类。
Suppose we're defining a React class that will display a tree.
React.createClass({
propTypes: {
tree: treeType
},
render: function () {
// ...
}
});
这是 treeType
的定义,显然不是不行,但希望说明我要表达的内容。
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?
推荐答案
React prop类型只是一个函数,因此可以像这样延迟引用:
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)
})
完整工作示例的其余代码(也可作为jsfiddle ):
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'));
结果屏幕截图:
< img src =https://i.stack.imgur.com/kOdUq.pngalt =结果截图>
这篇关于可以递归地定义React prop类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文