网站搜索

reactjs - 如何在 TypeScript 中将枚举用作 React 组件的默认属性值


我有一个枚举文件 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,所以默认值没有被正确设置。有没有办法使用枚举来设置这个默认主题值,以便它能正确评估?

编辑:最终有效的方法是将一个常量设置为枚举值,然后将其传递给 props

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

答案#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