gpt4 book ai didi

javascript - TypeScript:如何将 DefaultTheme 与样式组件结合起来?

转载 作者:行者123 更新时间:2023-12-05 02:39:42 25 4
gpt4 key购买 nike

我有一个由 styled-componentsexport a theme 组成的模块

我想将模块样式的导出主题与我的应用程序主题结合起来。

我在 theme.ts 中尝试了以下内容:

import { theme as idCheckTheme } from '@pass-culture/id-check/src/theme'
import { DefaultTheme } from 'styled-components/native'
import './styled.d'

export const theme: DefaultTheme = {
...idCheckTheme,
appBarHeight: 64,
}


我还复制了 styled.d.ts 并在顶部添加了 appBarHeight: number

当我启动我的应用程序时,出现以下错误:

Property 'appBarHeight' is missing in type '{ colors: { black: ColorsEnum; error: ColorsEnum; greenValid: ColorsEnum; greyDark: ColorsEnum; greyMedium: ColorsEnum; greyLight: ColorsEnum; ... 4 more ...; primaryDark: ColorsEnum; }; typography: { ...; }; buttons: { ...; }; }' but required in type 'DefaultTheme'.  TS2741

我希望它能工作,在 IntelliJ 中打字不会报错。

如何使用 TypeScript 将 styled-components 主题组合到新的 DefaultTheme 中?

最佳答案

您应该能够扩展 DefaultTheme 接口(interface),为您的主题创建一个接口(interface),并像这样定义它:

import { theme as idCheckTheme, ThemeType as IdCheckThemeType } from '@pass-culture/id-check/src/theme'
import { DefaultTheme } from 'styled-components/native'

// a declaration (d.ts) file may work better than declaring this above the interface
declare module 'styled-components' {
export interface DefaultTheme extends INewTheme {}
}

export interface INewTheme extends IdCheckThemeType{
appBarHeight: number;
}

export const NewTheme: INewTheme = {
...idCheckTheme,
appBarHeight: 64,
}

// pass your theme to your theme provider
<ThemeProvider theme={NewTheme}>
<App/>
</ThemeProvider>

在您的样式组件中,您还应该能够像这样访问 appBarHeight:

const StyledBar = styled.div`
${({theme}) => theme.appBarHeight};
`

关于javascript - TypeScript:如何将 DefaultTheme 与样式组件结合起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68956047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com