In my ponent I receive a prop called secondary which I deconstruct, and If that prop exist I want to pass it to another ponent, otherwise no:
...
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>
...
Is there another (simpler) way to do this?
In my ponent I receive a prop called secondary which I deconstruct, and If that prop exist I want to pass it to another ponent, otherwise no:
...
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>
...
Is there another (simpler) way to do this?
Share Improve this question asked Mar 6, 2019 at 7:34 Ana Laura T.Ana Laura T. 6702 gold badges10 silver badges22 bronze badges 1-
one possible way:
const secondaryProp = secondary ? {{ ...secondary, label: labelSecondary }} : {};
, then<MyChart {...secondaryProp}
– Mayank Shukla Commented Mar 6, 2019 at 7:40
2 Answers
Reset to default 3You could put your ternary condition inside your prop definition, if your variable is falsy, undefined
will be sent, and your prop will not be accessible :
<View>
<MyChart
selectedMandatory={selectedMandatory}
yAxis={yAxis}
mandatory={{ ...mandatory, label: labelMandatory }}
secondary={secondary ? { ...secondary, label: labelSecondary } : undefined}
quantity={quantity}
/>
</View>
You could fix/hack it like this:
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>
)
}
That way props.hasOwnProperty('secondary')
will be false if secondary
is not defined.
You could even pass in all props as a variable if that's more readable for you:
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>
)
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745362757a4624434.html
评论列表(0条)