[英]How to use an enum in typescript as a default prop value for a react component
I have an enum file Themes.ts
我有一个枚举文件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我想将该枚举用作<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>
)
}
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.我看到的问题是console.log(theme)
正在打印Themes.DEFAULT
而不是default
值,因此默认值设置不正确。 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 设置为枚举值,然后将其传递给道具
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.如果您尝试分配除'default'
或'dark'
之外的任何内容,TS 编译器将抛出错误。
Everything looks right.一切看起来都不错。 I tried to reproduce it but everything works fine https://codesandbox.io/s/interesting-spence-kw3og?file=/src/App.tsx我试图重现它,但一切正常https://codesandbox.io/s/interesting-spence-kw3og?file=/src/App.tsx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.