我有以下枚举
export enum Sizes{
Small,
Large
}
在我的<Demo/>
组件的道具界面中使用了
export interface IProps{
Label?: string;
Size: SizeEnum;
}
我的问题是,当我使用此<Demo Size={how do i define size here?} />
时?
答案 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)
type
或as const
在打字稿中,使用enum
被认为是一种不好且不可靠的做法。 type
和as 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 =...`
}