【发布时间】:2021-11-14 21:18:36
【问题描述】:
我在 Material UI 5.0 中使用 typescript 自定义主题时遇到问题。
主题.ts
import { createTheme } from '@mui/material';
declare module '@mui/material/styles' {
interface Theme {
custom: {
buttonWidth: string;
};
}
interface ThemeOptions {
custom: {
buttonWidth: string;
};
}
}
export const theme = createTheme({
palette: {
primary: {
main: '#00F',
},
},
typography: {
body1: {
fontFamily: 'Comic Sans',
},
},
custom: {
buttonWidth: '200px',
},
});
export const CustomTheme= typeof theme;
但是当我尝试使用它时,它不起作用
// CustomTheme imported
<Button sx={{ width: (theme: CustomTheme) => theme.custom.buttonWidth}} />
显示为 any 或者我有这个打字稿错误:
您的意思是“typeof CustomTheme”吗?
我的问题是使用 Material UI 5.0 和 typescript 实现自定义主题的正确方法是什么
package.json
// other dependencies
"@emotion/react": "^11.4.1",
"@emotion/styled": "^11.3.0",
"@mui/icons-material": "^5.0.0",
"@mui/material": "^5.0.0",
【问题讨论】:
-
如果可以请分享您的
<Button />组件 -
您是否将
Button与您的自定义主题放在ThemeProvider中? -
使用 useTheme 钩子可以获得正确的 Theme
标签: reactjs typescript material-ui