Javascript 如何为React中的嵌套形状提供默认道具?
React中是否有一种方法可以为特定形状的嵌套项目数组提供默认道具 给出下面的例子,可以看到我的第一次尝试,但是这并没有像预期的那样有效Javascript 如何为React中的嵌套形状提供默认道具?,javascript,reactjs,Javascript,Reactjs,React中是否有一种方法可以为特定形状的嵌套项目数组提供默认道具 给出下面的例子,可以看到我的第一次尝试,但是这并没有像预期的那样有效 static propTypes = { heading: PT.string, items: PT.arrayOf(PT.shape({ href: PT.string, label: PT.string, })).isRequired, }; static defaultProps = {
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 - ' },
]
};
没有。默认道具只是简单地合并 然而,一种方法可能是为每个项目都有一个子组件。这样,每个子组件从
项
数组中接收一个对象,然后默认的道具将按预期合并
例如:
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>
);
}
});
var Parent=React.createClass({
道具类型:{
标题:React.PropTypes.string,
项目:React.PropTypes.arrayOf(React.PropTypes.shape({
href:React.PropTypes.string,
标签:React.PropTypes.string,
})).需要
},
getDefaultProps:function(){
返回{
标题:“这很有效”,
项目:[{
href:“/”,
标签:'-这不是-',
}],
};
},
render:function(){
返回(
{this.props.item.map(函数(item)){
返回
})}
);
}
});
var Child=React.createClass({
道具类型:{
href:React.PropTypes.string,
标签:React.PropTypes.string
},
getDefaultProps:function(){
返回{
href:“/”,
标签:'-这不是-'
};
},
render:function(){
返回(
href:{this.props.href}
标签:{this.props.label}
);
}
});
您可以使用getter而不是调用this.props
。要想成为一种昂贵的方法,你必须有很多物品。您也可以像我下面所做的那样修改项
,然后将其设置为状态,但不进行响应
类Foo扩展了React.Component{
静态类型={
标题:PropTypes.string,
项目:PropTypes.arrayOf(PropTypes.shape({
href:PropTypes.string,
标签:PropTypes.string,
})).需要
}
静态defaultLabel='-这不是-'
静态defaultHref='/'
获取项目(){
返回此.props.items.map((项目)=>({
href:item.href | | this.defaultHref,
标签:item.label | | this.defaultLabel,
}));
}
render(){
返回(
{this.items.map(({href,label})=>)}
);
}
}
固溶体,但。。。不那么优雅。自从这篇文章发布后,React中是否有允许道具完全合并的更改?@RoyPrins据我所知,还没有