简体   繁体   中英

How to use an enum in typescript as a default prop value for a react component

I have an enum file Themes.ts

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

And I want to use that enum as a default prop in a <Test/> component that looks like

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>
    )
}

The issue i'm seeing is that console.log(theme) is printing Themes.DEFAULT instead of default so the default value isn't being set properly. Is there anyway to use an enum to set this default theme value so that it will evaluate properly?

EDIT : What ended up working was setting a const to the enum values and then passing that into the props

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

Use string union types instead of enums. This way you keep the same type strength and your strings can be strings.

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

Then in your component

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>
    )
}

If you try to assign anything besides 'default' or 'dark' , the TS compiler will throw an error.

Everything looks right. I tried to reproduce it but everything works fine https://codesandbox.io/s/interesting-spence-kw3og?file=/src/App.tsx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM