Chr*_*ris 32 javascript reactjs
在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 - ',
}],
};
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我希望如下:
// 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 - ' },
]
};
Run Code Online (Sandbox Code Playgroud)
Wic*_*ams 22
不会.默认道具只是浅层合并.
但是,一种方法可能是为每个项目设置一个子组件.这样每个Child组件从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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15226 次 |
| 最近记录: |