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

标签 javascript reactjs typescript styled-components tsx

我有一个由 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/

相关文章:

javascript - 列出包装 Shiny 传单的输入处理程序

javascript - selenium 找不到 chromedriver

node.js - 引用错误: Node is not defined (trying to use Node interface in typescript function in nodejs application)

javascript - 记录列表的 TypeScript 数据类型

javascript - 你能测试浏览器对 -moz-linear-gradient 的支持吗?

javascript - 将 JavaScript 与 JSF 和 Facelets 结合使用

javascript - ReactJs/Redux 不变违规 : Could not find "store" in either the context or props of "Connect(LoginContainer)"

javascript - 全局变量未按方法预期的方式更改

javascript - 如何将 HTML 组件添加到 React.js

javascript - Typescript Web 音频 API 缺少定义