在我的组件中,我收到了我解构的称为 secondary 的道具,如果存在该道具,我想将其传递给另一个组件,否则没有:
...
render() {
const { yAxis, mandatory, secondary, quantity } = this.props
...
return (
<View>
{secondary ? (
<MyChart
selectedMandatory={selectedMandatory}
yAxis={yAxis}
mandatory={{ ...mandatory, label: labelMandatory }}
secondary={{ ...secondary, label: labelSecondary }}
quantity={quantity}
/>
) : (
<MyChart
selectedMandatory
yAxis={yAxis}
mandatory={{ ...mandatory, label: labelMandatory }}
quantity={quantity}
/>
)}
</View>
...
是否有另一种(简单)的方法?
您可以像这样修复/黑客攻击:
render() {
var extraProps = {};
if(secondary) {
extraProps['secondary'] = { ...secondary, label: labelSecondary }
}
return (
<View>
<MyChart
selectedMandatory={selectedMandatory}
yAxis={yAxis}
mandatory={{ ...mandatory, label: labelMandatory }}
quantity={quantity}
{...extraProps}
/>
</View>
)
}
这样,如果未定义secondary
,则props.hasOwnProperty('secondary')
将是错误的。
,如果对您来说更可读性,您甚至可以将所有道具作为变量传递:
render() {
var allProps = {
selectedMandatory: selectedMandatory,
yAxis: yAxis,
mandatory: { ...mandatory, label: labelMandatory },
quantity: quantity
};
if(secondary) {
allProps['secondary'] = { ...secondary, label: labelSecondary }
}
return (
<View>
<MyChart
{...allProps}
/>
</View>
)
}
您可以将三元条件放在道具定义中,如果您的变量是虚假的,则将发送undefined
,并且您的道具将无法访问:
<View>
<MyChart
selectedMandatory={selectedMandatory}
yAxis={yAxis}
mandatory={{ ...mandatory, label: labelMandatory }}
secondary={secondary ? { ...secondary, label: labelSecondary } : undefined}
quantity={quantity}
/>
</View>