gpt4 book ai didi

javascript - 可以递归定义 React prop 类型吗?

转载 作者:可可西里 更新时间:2023-11-01 01:50:30 24 4
gpt4 key购买 nike

假设我们正在定义一个将显示树的 React 类。

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

这是 treeType 的定义,它显然不起作用,但希望能说明我要表达的意思。

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

有没有办法让类型懒惰地引用自己,这样就可以工作了?

最佳答案

React prop 类型只是一个函数,因此可以像这样延迟引用它:

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)
})

完整工作示例的其余代码 (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

关于javascript - 可以递归定义 React prop 类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com