网站搜索

reactjs - Emotion 11 在 TypeScript 和 React 中获取主题对象


目前我有以下结构:

src/styles/theme.ts
const theme = {
  fonts: {
    body: 'Lato, sans-serif',
  },
  colors: {
    primary: '#3D63AE',
  },
};

// export type ThemeProps = {
//   theme: Theme;
// };

export default theme;

在 src/types/emotion.d.ts 中:

import '@emotion/react';

declare module '@emotion/react' {
  export interface Theme {
    colors: {
      primary: string;
    };
    fonts: {
      body: string;
    };
  }
}

要输入我的 theme,我可以这样做:

import { Theme } from '@emotion/react';

const theme: Theme = {
 // ...

1) 这是首选且最干净的方式吗?

同样在例如我的 Header 组件样式文件 src/components/Header/Header.styles.ts 中,我也想访问我的 theme 对象。

我看到人们在做:

export type ThemeProps = {
 theme: Theme;
};

所以在 Header.styles.ts 中我可以这样做:

import { ThemeProps } from ???;
export default ({ theme }: ThemeProps) => ({
  root: css`
    margin-top: ${theme.spaces.large};
  `,

2) 但是我必须在哪里声明这个类型?

上述设置是推荐的方式吗?

更新:

我创建了一个全局声明文件 src/types/global.d.ts,并添加了:

import { Theme } from '@emotion/react';

declare global {
  interface ThemeProps {
    theme: Theme;
  }
}

现在在 Header.styles.ts 中我可以使用:

export default ({ theme }: ThemeProps) => ({
  root: css`
    margin-top: ${theme.spaces.large};
  `,