Emotion 11 使用打字稿访问主题对象并做出反应

时间:2021-04-25 09:03:24

标签: reactjs typescript emotion

目前我有以下结构:

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)这是首选和最干净的方式吗?

也在例如我的标题组件样式文件 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};
  `,

0 个答案:

没有答案