Twi*_*geh 7 emotion typescript
import '@emotion/react';
declare module '@emotion/react' {
export interface Theme {
colors: {
primaryColor: string;
accentColor: string;
};
}
}
Run Code Online (Sandbox Code Playgroud)
import { Theme, ThemeProvider } from '@emotion/react';
const theme: Theme = {
colors: {
accentColor: 'hotpink',
primaryColor: 'aqua',
},
};
...
return (
<ThemeProvider theme={theme}>
...
Run Code Online (Sandbox Code Playgroud)
const StyledButton = styled.a`
${({ theme }) =>
`background-color: ${theme.colors.accentColor};`
}`;
Run Code Online (Sandbox Code Playgroud)
import '@emotion/react';
declare module '@emotion/react' {
export interface Theme {
colors: {
primaryColor: string;
accentColor: string;
};
}
}
Run Code Online (Sandbox Code Playgroud)
src
|=>@types
|> emotion.d.ts
|=> components
|> App.tsx
Run Code Online (Sandbox Code Playgroud)
属性“颜色”在类型“对象”上不存在。
我做错了什么还是我误读了文档?
现在,我通过将主题传递给样式构造函数来手动添加主题:
type StyledProps = Pick<ButtonProps, 'bgColor' | 'fColor'> & { theme: Theme };
const StyledButton = styled.a<StyledProps>`
...
Run Code Online (Sandbox Code Playgroud)
删除传递的类型也没有帮助。
似乎 d.ts 文件已正确拾取,因为我可以从"@emtion/react"with导入正确的主题类型并使用它在样式组件中import { Theme } from "@emotion/react"键入props.theme
根据您提供的代码,我认为错误应该是:
Property 'accentColor' does not exist on type 'Theme'. // instead of object
Run Code Online (Sandbox Code Playgroud)
无论如何,您的Theme对象现在嵌套colors在顶层,因此您可以更改为:
Property 'accentColor' does not exist on type 'Theme'. // instead of object
Run Code Online (Sandbox Code Playgroud)
请记住,您还需要在构建过程中包含您定义的类型tsconfig.json通过选项将您定义的类型包含在文件的构建过程中include。
Theme通过自定义类型文件覆盖的更新正如我所见,该styled类型仅消耗Theme来自的对象@emotion/react至少来自 version 的^11.0.0。
简而言之,您必须@emotion/styled从该版本更新到^11.0.0它才能按预期工作:
{
"dependencies": {
// ...
"@emotion/styled": "^11.0.0",
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6413 次 |
| 最近记录: |