簡體   English   中英

如何使用打字稿中的枚舉作為反應組件的默認道具值

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

我有一個枚舉文件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) => {

使用字符串聯合類型而不是枚舉。 這樣,您可以保持相同的類型強度,並且您的琴弦可以是琴弦。

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 編譯器將拋出錯誤。

一切看起來都不錯。 我試圖重現它,但一切正常https://codesandbox.io/s/interesting-spence-kw3og?file=/src/App.tsx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM