Một Phản ứng kiểu prop chỉ là một chức năng, vì vậy nó có thể được tham chiếu uể oải như thế này:
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)
})
Phần còn lại của mã cho một ví dụ làm việc đầy đủ (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'));
Ảnh chụp màn hình của kết quả:
Nguồn
2015-08-19 10:24:22
Cảm ơn fo r giải pháp của bạn. Tôi đang tìm kiếm điều tương tự -> https://github.com/facebook/react/issues/5676 –