将TypeScript类型作为道具传递给React组件?

时间:2020-04-07 12:14:13

标签: reactjs typescript

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

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

<MyComponent activity={ActivitiesType.RUN} />

然后在MyComponent中:

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

1 个答案:

答案 0 :(得分:1)

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

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

type Props = {
  type: ActivitiesType;
}