2015-08-18 13 views
11

Giả sử chúng ta định nghĩa một lớp React sẽ hiển thị một cây.Loại phản kháng có thể được định nghĩa đệ quy không?

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

Đây là định nghĩa của treeType rõ ràng là không hoạt động nhưng hy vọng minh họa những gì tôi đang cố gắng thể hiện.

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

Có cách nào để loại này tự đề cập một cách lười biếng để điều này có thể hoạt động không?

+0

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 –

Trả lời

13

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ả:

Screenshot of the result

+0

Một số lý do không sử dụng chỉ: var lazyTreeType = function() { trả về treeType.apply (điều này, đối số) ; }; –

+0

@FelipeT. Tôi cũng tò mò về điều này – sookie

Các vấn đề liên quan