2016-06-30 25 views
14

React中有一種方法可以爲特定形狀的項目的嵌套數組提供默認道具嗎?如何爲React中的嵌套形狀提供默認道具?

給出下面的例子,我可以看到第一次嘗試,但是這並不像預期的那樣工作。

static propTypes = { 
    heading: PT.string, 
    items: PT.arrayOf(PT.shape({ 
     href: PT.string, 
     label: PT.string, 
    })).isRequired, 
}; 

static defaultProps = { 
    heading: 'this works', 
    items: [{ 
     href: '/', 
     label: ' - this does not - ', 
    }], 
}; 

在這個例子中,我希望以下內容:

// Given these props 
const passedInProps = { 
    items: [{ href: 'foo', href: 'bar' }] 
}; 

// Would resolve to: 
const props = { 
    heading: 'this works', 
    items: [ 
     { href: 'foo', label: ' - this does not - ' }, 
     { href: 'bar', label: ' - this does not - ' }, 
    ] 
}; 

回答

14

號默認道具只淺合併。

但是,一種方法可能是爲每個項目設置一個子組件。這樣,每個子組件都會從item數組中接收一個對象,然後按照您的預期合併默認道具。

例如:

var Parent = React.createClass({ 

    propTypes: { 
    heading: React.PropTypes.string, 
    items: React.PropTypes.arrayOf(React.PropTypes.shape({ 
     href: React.PropTypes.string, 
     label: React.PropTypes.string, 
    })).isRequired 
    }, 

    getDefaultProps: function() { 
    return { 
     heading: 'this works', 
     items: [{ 
     href: '/', 
     label: ' - this does not - ', 
     }], 
    }; 
    }, 

    render: function() { 
    return (
     <div> 
     {this.props.item.map(function(item) { 
      return <Child {...item} /> 
     })} 
     </div> 
    ); 
    } 

}); 

var Child = React.createClass({ 

    propTypes: { 
    href: React.PropTypes.string, 
    label: React.PropTypes.string 
    }, 

    getDefaultProps: function() { 
    return { 
     href: '/', 
     label: ' - this does not - ' 
    }; 
    }, 

    render: function() { 
    return (
     <div /> 
     <p>href: {this.props.href}</p> 
     <p>label: {this.props.label} 
     </div> 
    ); 
    } 

});