【问题标题】:EmotionJS with typescript doesn't pass theme type to props in styled components带有打字稿的 EmotionJS 不会将主题类型传递给样式化组件中的道具
【发布时间】:2021-03-27 12:56:19
【问题描述】:

emotion.d.ts

import '@emotion/react';

declare module '@emotion/react' {
    export interface Theme {
        colors: {
            primaryColor: string;
            accentColor: string;
        };
    }
}

App.tsx

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

const theme: Theme = {
    colors: {
        accentColor: 'hotpink',
        primaryColor: 'aqua',
    },
};
...

return (
<ThemeProvider theme={theme}>

...

Button.tsx

const StyledButton = styled.a`
    ${({ theme }) =>
        `background-color: ${theme.colors.accentColor};`
    }`;

tsconfig.json

{
    "compilerOptions": {
        "target": "es6",
        "allowSyntheticDefaultImports": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "typeRoots": ["src/@types"],
        "jsx": "react",
        "strict": true,
        "strictNullChecks": true,
        "baseUrl": "./",
        "paths": {
            "*": ["src/@types/*"]
        }
    },
    "compileOnSave": false,
    "include": ["src/**/*"]
}
src
|=>@types
  |> emotion.d.ts
|=> components
|> App.tsx

“对象”类型上不存在属性“颜色”。

是我做错了什么还是我误读了文档?

现在我通过将主题传递给样式构造函数来手动添加主题:


type StyledProps = Pick<ButtonProps, 'bgColor' | 'fColor'> & { theme: Theme };

const StyledButton = styled.a<StyledProps>`
...

删除传递的类型也无济于事。

d.ts 文件似乎被正确拾取,因为我可以从 "@emtion/react"import { Theme } from "@emotion/react" 导入正确的主题类型,并使用它在样式组件中键入 props.theme

Repro

【问题讨论】:

    标签: typescript emotion


    【解决方案1】:

    根据您提供的代码,我认为错误应该是:

    Property 'accentColor' does not exist on type 'Theme'. // instead of object
    

    无论如何,您的 Theme 对象现在嵌套在顶层的 colors 中,因此您可以更改为:

    const StyledButton = styled.a`
      ${({ theme }) =>
          `background-color: ${theme.colors.accentColor};` // `accentColor` is nested in `colors`
      }`;
    
    

    请记住,您还需要通过include 选项将您定义的类型包含在tsconfig.json 文件中的构建过程中。

    关于无法通过自定义类型文件覆盖Theme的更新

    正如我所见,styled 类型只消耗来自@emotion/reactTheme 对象,至少来自版本^11.0.0

    简而言之,您必须从这个版本更新 @emotion/styled^11.0.0 才能使其按预期工作:

    {
      "dependencies": {
        // ...
        "@emotion/styled": "^11.0.0",
      }
    }
    

    【讨论】:

    • 是的,这是问题中的拼写错误,而不是实际代码,抱歉。我很快就会添加我的文件结构和 tsconfig
    • 用给定的代码看起来没什么奇怪的。你有可重复的回购吗?
    • 是的,刚刚将它和一个错误报告添加到emotionjs
    • 现在好像是空的?
    • 是的,我在尝试推送时遇到了 econnreset 错误。现在应该好了
    猜你喜欢
    • 2021-10-14
    • 2021-11-18
    • 2021-11-10
    • 2021-06-29
    • 2020-10-28
    • 1970-01-01
    • 2021-03-04
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多