如何使用enum作为react / typescript中的道具

时间:2018-04-10 06:18:19

标签: reactjs typescript enums

我有以下枚举

export enum Sizes{
    Small,
    Large
}

在我的<Demo/>组件的道具界面中使用了

export interface IProps{
    Label?: string;
    Size: SizeEnum;
}

我的问题是,当我使用此<Demo Size={how do i define size here?} />时?

2 个答案:

答案 0 :(得分:5)

您可以像在任何其他上下文中一样引用枚举值:

export enum Sizes{
    Small,
    Large
}

export interface IProps{
    Label?: string;
    Size: Sizes;
}

class Demo extends React.Component<IProps> {}

let d = <Demo Size={Sizes.Large} />

答案 1 :(得分:1)

使用typeas const

在打字稿中,使用enum被认为是一种不好且不可靠的做法。 typeas const都具有自动填充功能,并且在使用无效值时会抱怨。

类型

type MyEnum = 'up' | 'down' | 'left' | 'right'

Use:
'up'

interface IProps {
    Size: MyEnum
}

为常量

const MyEnum = {
    Up: 'up',
    Down: 'down',
    Left: 'left',
    Right: 'right',
} as const

type MyEnum = typeof MyEnum[keyof typeof MyEnum]

Use:
MyEnum.Up

interface IProps {
    Size: MyEnum // string, without line `type MyEnum =...`
}

More detail on as const and freezing parameters