注意! 我已經通過在下面的宣告中使用 "theme: any "來緩解這個問題,但我希望有更好的方法。
我在前端使用 React(v17.0.2)和 material-ui(v5.0.0),我得到了如下錯誤:
屬性'palette'不存在于'Theme'型別上。
每當我試影像這樣訪問我的主題時:
span class="hljs-keyword">import { useTheme } from '@emotion/react'/span>;
export default function MyComponent() {
const theme = useTheme()
return (
<Box()
sx={{}。
backgroundColor: theme.palette.mode === 'dark'/span> ? 'primary.dark' : 'primary' 。
}}
></Box>
);
}
我在宣告下面用console.log(theme)記錄了這個物件,它成功地記錄了我的主題。所以它是存在的,但我不能像上面顯示的那樣訪問它。
以下是一些被記錄的內容:
{breakpoints: {...}, direction: 'ltr', components: {...}, palette: {...}, spacing: ?, ...}
> breakpoints: {keys: Array(5), ...}。
> components: {MuiTypography: {...}, ... }
direction: "ltr": "ltr".
> mixins: {toolbar: {...}}
> palette: {mode: 'dark', ...}。
...
另外,我找到了型別 "Theme "所在的檔案,屬性 "palette "肯定存在。下面是該檔案的一個片段:
export 介面 Theme extends SystemTheme {
mixins: Mixins;
組件? Components。
palette: Palette;
陰影。Shadows;
transitions: 過渡。
typography: 型別學。
zIndex: ZIndex。
unstable_strictMode? : boolean。
}
我還試著像這樣匯入和使用Theme:
import { Theme } from '@mui/material/styles' ;
...
const theme: Theme = useTheme()
...
這又給了我一個新的錯誤(在 "theme "變數下劃線):
。型別'Theme'缺少了型別'Theme'的以下屬性:混合器、調色板、陰影、過渡,以及其他6個。
我也這樣試過:
import { Theme } from '@mui/material/styles' ;
...
const theme = useTheme<Theme> ()
...
這又給了我一個新的錯誤(在useTheme<Theme>()中的 "主題 "下劃線)
預計0個型別引數,但得到了1個。
而且還
屬性'調色板'在型別'Theme'上不存在。
我是 typecript 的新手,所以希望得到任何幫助。
編輯 得到了答案,感謝Alex Wayne(如果我最初誤解了答案,也許還有windowsill)。以下是起作用的代碼:
import { useTheme, Theme } from '@mui/material'/span>;
const theme: Theme = useTheme()
<Box sx={{backgroundColor: theme. palette.mode}}> </Box>
uj5u.com熱心網友回復:
@emotion/react匯出一個Theme型別,由同一包的useTheme()回傳。@mui/material/styles匯出一個Theme型別,該型別由來自同一包的createTheme回傳。- 這些不是同一個型別。
它們在每個包中都有相同的名字,但完全不相關。
這就是為什么會失敗的原因:
import { useTheme } from '@emotion/react'/span>;
import { Theme } from '@mui/material/styles'/span>;
const theme: Theme = useTheme()
//Type 'Theme' is missing the following properties from type 'Theme': mixins, palette, shadows, transitions, and 2 more. (2740)
但這是成功的。
import { useTheme, Theme } from '@emotion/react'/span>;
const theme: Theme = useTheme()
我不知道您打算使用哪一種,但是這里有關于情感主題的檔案,以及這里有關于 Material UI 主題的檔案。它們是不同的東西,您需要根據它們的預期用途來使用它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/332289.html
標籤:
下一篇:如何隱藏/不隱藏密碼材料uI
