传递有条件的道具的更清洁的方式

Cleaner way to pass a prop with conditions

我有一个组件可以接受这样的道具:

   <Description
    priceValue={
      product.price && isOutlet
        ? product.price_outlet === '0'
          ? ''
          : `${product.price_outlet}`
        : `${product.price}`
    }
    />

我不想把所有这些条件都放在 priceValue 属性中。

我的解决方案是:

 const PriceBox = () => {
          return product.price && isOutlet
            ? product.price_outlet === '0'
              ? ''
              : `${product.price_outlet} ${product.currencySymbol}`
            : `${product.price} ${product.currencySymbol}`;
        };

   <Description priceValue={<PriceBox/>}/>

如果有更简洁的实现方法,谁能给我提示?

提前致谢

您可以在渲染之前将逻辑提取到变量中:

const priceValue = (
  product.price && isOutlet
    ? (product.price_outlet === '0'
      ? ''
      : `${product.price_outlet}`)
    : `${product.price}`
);

return (
  <Description priceValue={priceValue} />
);

或者,如果您愿意,函数:

const getPriceValue = () => (
  product.price && isOutlet
    ? (product.price_outlet === '0'
      ? ''
      : `${product.price_outlet}`)
    : `${product.price}`
);

return (
  <Description priceValue={getPriceValue()} />
);

如果 this 的上下文在类似 map() 操作的范围内,则该函数可能是首选,其中每个元素的 product 可能不同。例如:

const getPriceValue = (product) => (
  product.price && isOutlet
    ? (product.price_outlet === '0'
      ? ''
      : `${product.price_outlet}`)
    : `${product.price}`
);

return (
  <>
    {products.map(product => (
      <Description priceValue={getPriceValue(product)} />
    ))}
  </>
);

一种方法是赋值给一个变量,然后作为props传入。

例如:

const priceValue = product.price && isOutlet ? product.price_outlet === '0' ? '' : product.price_outlet: product.price

或者,您可以使用更易于阅读的 if 语句:

let priceValue;

if (product.price && isOutlet) {
    if (product.price_outlet === '0') {
        priceValue = ""
    } else {
        priceValue = product.price_outlet
    }
} else {
    priceValue = product.price
}

在这些解决方案中的任何一个之后,您都可以传递 priceValue={priceValue}Description 组件道具。这将使查看您返回的内容更容易阅读。