有条件地将道具传递给组件

问题描述 投票:0回答:2

在我的组件中,我收到了一个名为secondary的prop我解构,如果该prop存在,我想将它传递给另一个组件,否则不:

...
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>
   ...

还有另一种(更简单的)方法吗?

javascript reactjs react-native
2个回答
1
投票

你可以像这样修复/破解它:

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>
    )
}

这样,如果没有定义props.hasOwnProperty('secondary')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>
    )
}

1
投票

你可以把你的三元条件放在你的道具定义中,如果你的变量是假的,那么undefined将被发送,你的道具将无法访问:

<View>
    <MyChart
        selectedMandatory={selectedMandatory}
        yAxis={yAxis}
        mandatory={{ ...mandatory, label: labelMandatory }}
        secondary={secondary ? { ...secondary, label: labelSecondary } : undefined}
        quantity={quantity}
    />
</View>
© www.soinside.com 2019 - 2024. All rights reserved.