React 中有没有一种方法可以为特定形状的嵌套项目数组提供默认 Prop ?
给出下面的示例,可以看到我的第一次尝试,但是这并没有按预期工作。
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 - ' },
]
};
最佳答案
没有。默认 Prop 只是浅合并。
但是,一种方法可能是为每个项目设置一个子组件。这样每个 Child 组件都会从 item
数组中接收一个对象,然后默认的 props 将按照您的预期合并。
例如:
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>
);
}
});
关于javascript - 你如何在 React 中为嵌套形状提供默认 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38123498/