2016-06-30 5 views
14

特定の形状のアイテムのネストされた配列にデフォルトの小道具を提供する方法はありますか?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

番デフォルトの小道具は浅くマージされます。

しかし、1つのアプローチでは、各アイテムに子コンポーネントを持たせることが考えられます。そうすれば、各子コンポーネントはitem配列から1つのオブジェクトを受け取り、デフォルトの小道具が期待どおりにマージされます。例えば

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

}); 
関連する問題