【问题标题】:How to use an enum in typescript as a default prop value for a react component如何使用打字稿中的枚举作为反应组件的默认道具值
【发布时间】:2021-07-20 14:53:23
【问题描述】:

我有一个枚举文件Themes.ts

export enum Themes {
    DEFAULT = 'default',
    DARK = 'dark'
}

我想将该枚举用作<Test/> 组件中的默认道具,看起来像

export type TestProps = {
    children: ReactChild,
    theme?: Themes,
}

export const Test = ({ children, theme = Themes.DEFAULT }: TestProps) => {
    console.log(theme)
    return (
        <div className={`${theme}`}>
            <div>
                { children }
            </div>
        </div>
    )
}

我看到的问题是console.log(theme) 正在打印Themes.DEFAULT 而不是default,因此默认值设置不正确。无论如何使用枚举来设置这个默认主题值,以便它能够正确评估?

编辑: 最终的工作是将 const 设置为枚举值,然后将其传递给道具

const enumValue = Themes.DEFAULT
export const Test = ({ children, theme = enumValue }: TestProps) => {

【问题讨论】:

    标签: reactjs typescript enums


    【解决方案1】:

    使用字符串联合类型而不是枚举。这样你就可以保持相同的类型强度,并且你的字符串可以是字符串。

    export type Themes = 'default' | 'dark';
    

    然后在你的组件中

    export type TestProps = {
        children: ReactChild,
        theme?: Themes,
    }
    
    export const Test = ({ children, theme = 'default' }: TestProps) => {
        console.log(theme)
        return (
            <div className={`${theme}`}>
                <div>
                    { children }
                </div>
            </div>
        )
    }
    

    如果您尝试分配除'default''dark' 之外的任何内容,TS 编译器将抛出错误。

    【讨论】:

    • 这很有用,但不是我想要的。希望避免在代码中硬编码字符串
    • 它可能看起来只是对字符串进行硬编码。但它分配了这种类型接受的两个可能值之一。就像使用枚举一样。
    【解决方案2】:

    一切看起来都不错。我试图重现它,但一切正常 https://codesandbox.io/s/interesting-spence-kw3og?file=/src/App.tsx

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2019-12-27
      • 2019-07-09
      • 2022-08-03
      • 2016-05-08
      相关资源
      最近更新 更多