【发布时间】: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
}
}
【问题讨论】:
-
我不确定是否有可能,因为运行时类型不存在。为什么不在活动中使用字段
type? Here 更多来自官方文档 -
为什么不使用枚举?
-
您正在寻找泛型,请阅读此stackoverflow.com/questions/57208569/… 可能是重复的
-
相关:How do the different enum variants work in TypeScript?。您的类型本质上是环境枚举。你需要一个在运行时存在的真实的。
标签: reactjs typescript