Sea*_*ean 3 typescript reactjs material-ui
笔记!我已经通过在下面的声明中使用“主题:任意”来设法缓解这个问题,但我更喜欢更好的方法。
\n我将 React (v17.0.2) 与 Material-ui (v5.0.0) 一起用于前端,但出现以下错误:
\n\n\n“主题”类型上不存在属性“调色板”。
\n
每当我尝试像这样访问我的主题时:
\nimport { useTheme } from '@emotion/react';\n\nexport default function MyComponent() {\n\n const theme = useTheme()\n\n return (\n <Box\n sx={{\n backgroundColor: theme.palette.mode === 'dark' ? 'primary.dark' : 'primary',\n }}\n ></Box>\n );\n}\nRun Code Online (Sandbox Code Playgroud)\n我记录了该对象console.log(theme)我在声明下方所以它就在那里,但我无法像上面所示访问它。\n以下是记录的一些内容:
{breakpoints: {\xe2\x80\xa6}, direction: 'ltr', components: {\xe2\x80\xa6}, palette: {\xe2\x80\xa6}, spacing: \xc6\x92,\xc2\xa0\xe2\x80\xa6}\n > breakpoints: {keys: Array(5), ...}\n > components: {MuiTypography: {\xe2\x80\xa6}, ...}\n direction: "ltr"\n > mixins: {toolbar: {...}}\n > palette: {mode: 'dark', ...}\n ...\nRun Code Online (Sandbox Code Playgroud)\n另外,我找到了“主题”类型所在的文件,并且属性“调色板”肯定存在。这是该文件的片段:
\nexport interface Theme extends SystemTheme {\n mixins: Mixins;\n components?: Components;\n palette: Palette;\n shadows: Shadows;\n transitions: Transitions;\n typography: Typography;\n zIndex: ZIndex;\n unstable_strictMode?: boolean;\n}\nRun Code Online (Sandbox Code Playgroud)\n我还尝试像这样导入和使用主题:
\nimport { Theme } from '@mui/material/styles';\n...\nconst theme: Theme = useTheme()\n...\nRun Code Online (Sandbox Code Playgroud)\n这给了我一个新的错误(强调“主题”变量):
\n\n\n“主题”类型缺少“主题”类型中的以下属性:mixins、调色板、阴影、过渡等 6 个属性。
\n
我也尝试过这样的:
\nimport { Theme } from '@mui/material/styles';\n...\nconst theme = useTheme<Theme>()\n...\nRun Code Online (Sandbox Code Playgroud)\n这给了我一个新的错误(在 useTheme< Theme中强调“主题” >() 中强调“主题”)
\n\n\n预期有 0 个类型参数,但得到了 1 个。
\n
并且
\n\n\n“主题”类型上不存在属性“调色板”。
\n
我是打字稿新手,因此非常感谢任何帮助。
\n编辑\n感谢亚历克斯·韦恩(Alex Wayne)得到了答案(如果我最初误解了答案,也许还有窗台)。这是有效的代码:
\nimport { useTheme, Theme } from '@mui/material';\nconst theme: Theme = useTheme()\n<Box sx={{backgroundColor: theme.palette.mode}}></Box>\nRun Code Online (Sandbox Code Playgroud)\n
为了获得正确的类型检查,您可以使用 MUI 扩展情感主题界面。
import { Theme as MuiTheme } from "@mui/material/styles";
declare module '@emotion/react' {
export interface Theme extends MuiTheme {}
}
Run Code Online (Sandbox Code Playgroud)
如 https://emotion.sh/docs/typescript#define-a-theme中指定
@emotion/react导出一个类型,由同一个包Theme返回。useTheme()@mui/material/styles导出一个类型,由同一个包Theme返回。createTheme它们在每个包中具有相同的名称,但完全不相关。
这就是失败的原因:
import { useTheme } from '@emotion/react';
import { Theme } from '@mui/material/styles';
const theme: Theme = useTheme()
// Type 'Theme' is missing the following properties from type 'Theme': mixins, palette, shadows, transitions, and 2 more.(2740)
Run Code Online (Sandbox Code Playgroud)
但这成功了。
import { useTheme, Theme } from '@emotion/react';
const theme: Theme = useTheme()
Run Code Online (Sandbox Code Playgroud)
我不确切知道您打算使用哪一个,但这里是关于情感主题的文档,这里是关于 Material UI 主题的文档。它们是独立的东西,您需要根据它们的预期用途来使用它们。
| 归档时间: |
|
| 查看次数: |
13865 次 |
| 最近记录: |