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

时间:2019-03-06 07:34:52

标签: javascript reactjs react-native

在我的组件中,我收到了一个名为 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>
   ...

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

2 个答案:

答案 0 :(得分:1)

您可以将三元条件放在prop定义中,如果您的变量是虚假的,将发送undefined,并且prop无法访问:

<View>
    <MyChart
        selectedMandatory={selectedMandatory}
        yAxis={yAxis}
        mandatory={{ ...mandatory, label: labelMandatory }}
        secondary={secondary ? { ...secondary, label: labelSecondary } : undefined}
        quantity={quantity}
    />
</View>

答案 1 :(得分: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将为假。

如果您更容易理解,甚至可以将所有props作为变量传递:

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