gpt4 book ai didi

reactjs - typescript 错误说类型上不存在属性

转载 作者:行者123 更新时间:2023-12-05 08:19:35 28 4
gpt4 key购买 nike

注意!我已经设法通过在下面的声明中使用“主题:任何”来缓解这个问题,但我更喜欢更好的方法。

我将 React (v17.0.2) 用于带有 material-ui (v5.0.0) 的前端,但出现以下错误:

Property 'palette' does not exist on type 'Theme'.

每当我尝试像这样访问我的主题时:

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

export default function MyComponent() {

const theme = useTheme()

return (
<Box
sx={{
backgroundColor: theme.palette.mode === 'dark' ? 'primary.dark' : 'primary',
}}
></Box>
);
}

我在声明下方使用 console.log(theme) 记录了对象,它成功地记录了我的主题。所以它就在那里,但我无法像上面显示的那样访问它。以下是一些已记录的内容:

{breakpoints: {…}, direction: 'ltr', components: {…}, palette: {…}, spacing: ƒ, …}
> breakpoints: {keys: Array(5), ...}
> components: {MuiTypography: {…}, ...}
direction: "ltr"
> mixins: {toolbar: {...}}
> palette: {mode: 'dark', ...}
...

另外,我找到了类型“Theme”所在的文件,并且属性“palette”肯定存在。这是该文件的一个片段:

export interface Theme extends SystemTheme {
mixins: Mixins;
components?: Components;
palette: Palette;
shadows: Shadows;
transitions: Transitions;
typography: Typography;
zIndex: ZIndex;
unstable_strictMode?: boolean;
}

我也试过像这样导入和使用主题:

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 6 more.

我也这样试过:

import { Theme } from '@mui/material/styles';
...
const theme = useTheme<Theme>()
...

这给了我一个新的错误(在 useTheme<Theme>() 中强调“Theme”)

Expected 0 type arguments, but got 1.

还有

Property 'palette' does not exist on type 'Theme'.

我是 typescript 的新手,所以感谢任何帮助。

编辑感谢 Alex Wayne 得到了答案(如果我最初误解了答案,也许还有窗台)。这是有效的代码:

import { useTheme, Theme } from '@mui/material';
const theme: Theme = useTheme()
<Box sx={{backgroundColor: theme.palette.mode}}></Box>

最佳答案

为了获得正确的类型检查,您可以使用 MUI 扩展情感主题界面。

import { Theme as MuiTheme } from "@mui/material/styles";

declare module '@emotion/react' {
export interface Theme extends MuiTheme {}
}

如指定 https://emotion.sh/docs/typescript#define-a-theme

关于reactjs - typescript 错误说类型上不存在属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69272996/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com