简体   繁体   English

如何在 React 应用程序中向我的 Switch 语句添加另一个道具

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

I have a React component based on a type prop I am returning jsx.我有一个基于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;

How do I add the show prop here in a clean way?如何以干净的方式在此处添加show道具? When show === true I want to show the specific <div> otherwise return null (nothing)show === true我想显示特定的<div>否则返回null (什么都没有)


This is how the switch case works:这是开关盒的工作原理:

  1. The switch expression is evaluated once. switch 表达式被评估一次。
  2. The value of the expression is compared with the values of each case.将表达式的值与每个案例的值进行比较。
  3. If there is a match, the associated block of code is executed.如果匹配,则执行关联的代码块。
  4. If there is no match, the default code block is executed.如果没有匹配,则执行默认代码块。

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