【问题标题】:Pass a TypeScript Type as a prop to a React component?将 TypeScript 类型作为道具传递给 React 组件?
【发布时间】:2020-04-07 12:14:13
【问题描述】:

是否可以将 TypeScript 类型作为 prop 传递给 React 组件?

export type ActivitiesType = {
  RUN: "RUN";
  WALK: "REST";
  ROUNDS: "ROUNDS";
};

<MyComponent activity={ActivitiesType.RUN} />

然后在 MyComponent 中:

const MyComponent = ({ activity }) => {
  if(activity === ActivitiesType.RUN) {
    // Do something
  }
}

【问题讨论】:

标签: reactjs typescript


【解决方案1】:

Ritaj 是对的,Enums 可以做到这一点:

enum ActivitiesType {
  RUN: "RUN";
  WALK: "REST";
  ROUNDS: "ROUNDS";
}

type Props = {
  type: ActivitiesType;
}

【讨论】:

    猜你喜欢
    • 2018-08-22
    • 2020-03-12
    • 2018-08-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2018-06-04
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多