【问题标题】:How to use enum as props in react/typescript如何在反应/打字稿中使用枚举作为道具
【发布时间】:2018-09-19 15:51:02
【问题描述】:

我有以下枚举

export enum Sizes{
    Small,
    Large
}

在我的<Demo/> 组件的 props 接口中使用:

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

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

【问题讨论】:

    标签: reactjs typescript enums


    【解决方案1】:

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

    export enum Sizes{
        Small,
        Large
    }
    
    export interface IProps{
        Label?: string;
        Size: Sizes;
    }
    
    class Demo extends React.Component<IProps> {}
    
    let d = <Demo Size={Sizes.Large} />
    

    【讨论】:

    • 我需要在渲染Demo的组件中重新定义枚举吗?
    • 不,您应该能够像从任何其他类型一样从定义它的模块导入
    • 类似import { Demo, Sizes} from "../src/Demo.tsx"; ?
    • 但是当我做 SizeEnum.Small 时,我没有得到小或大的智能感知
    • 我愿意,你的枚举名称是什么? SizeSizeEnum ?您似乎同时使用两者,您应该定义枚举名称
    【解决方案2】:

    使用typeas const

    typeas const 都具有自动填充功能,并且在使用无效值时会报错。

    类型

    'up'   
    

    实现:

    type MyEnum = 'up' | 'down' | 'left' | 'right'
    
    interface IProps {
      Size: MyEnum
    }
    

    作为常量

    MyEnum.Up    
    

    实现:

    const MyEnum = {
      Up: 'up',
      Down: 'down',
      Left: 'left',
      Right: 'right',
    } as const
    
    type MyEnum = typeof MyEnum[keyof typeof MyEnum]
    
    // Example type
    interface IProps {
      Size: MyEnum // string, without line `type MyEnum =...`
    }
    

    More detail on as const and freezing parameters

    【讨论】:

    • 参考“......在打字稿中被认为是一种糟糕且不可靠的做法”这句话会很好吗?
    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 2020-01-29
    • 2017-02-03
    • 2022-08-03
    • 2020-08-21
    • 2019-07-09
    • 1970-01-01
    • 2019-03-13
    相关资源
    最近更新 更多