2016-06-30 26 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> 
    ); 
    } 

});