簡體   English   中英

如何在 React 應用程序中向我的 Switch 語句添加另一個道具

[英]How to add another prop to my Switch statement in React app

我有一個基於type道具的 React 組件,我正在返回 jsx。

type Props = {
  variant: 'type-one' | 'type-two' | 'type-three';
  show: boolean;
};

const Placeholder = ({ type, show }: Props) => {
  switch (variant) {
    case 'type-one':
      return (
        <div id="type-one" className="type-one" />
      );
    case 'type-two':
      return (
        <div id="type-two" className="type-two" />
      );
    case 'type-three':
      return (
        <div id="type-three" className="type-three" />
      );
    default:
      return null;
  }
};

export default Placeholder;

如何以干凈的方式在此處添加show道具? show === true我想顯示特定的<div>否則返回null (什么都沒有)


這是開關盒的工作原理:

  1. switch 表達式被評估一次。
  2. 將表達式的值與每個案例的值進行比較。
  3. 如果匹配,則執行關聯的代碼塊。
  4. 如果沒有匹配,則執行默認代碼塊。

const Placeholder = ({ variant, show }: Props) => {
if(show){
  switch (variant) {
    case 'type-one':
      return (
        <div id="type-one" className="type-one" />
      );
    case 'type-two':
      return (
        <div id="type-two" className="type-two" />
      );
    case 'type-three':
      return (
        <div id="type-three" className="type-three" />
      );
    default:
      return null;
  }
}
else {
   return null;
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM