【问题标题】:Material UI 5.0 Typescript React Custom themeMaterial UI 5.0 Typescript React 自定义主题
【发布时间】: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",

【问题讨论】:

  • 如果可以请分享您的&lt;Button /&gt; 组件
  • 您是否将Button 与您的自定义主题放在ThemeProvider 中?
  • 使用 useTheme 钩子可以获得正确的 Theme

标签: reactjs typescript material-ui


【解决方案1】:

在材质 v5 中,您可以使用 styleOverrides 覆盖默认样式

const theme = createTheme({
  palette: {
    primary: {
      main: '#00F',
    },
  },
  typography: {
    body1: {
      fontFamily: 'Comic Sans',
    },
  },
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          width: 200,
        },
      },
    },
  },
})

这种风格将应用于每一个Button

参考链接:https://mui.com/customization/theme-components/#global-style-overrides

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 2019-05-24
    • 2020-07-05
    • 2018-11-11
    • 2019-02-06
    • 2019-07-15
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多