Material UI 5.0 Typescript React 自定义主题

Spo*_*ngi 6 typescript reactjs material-ui

我在使用 TypeScript 在 Material UI 5.0 中自定义主题时遇到问题。

主题.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;
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用它时,它不起作用

// CustomTheme imported
<Button sx={{ width: (theme: CustomTheme) => theme.custom.buttonWidth}} />
Run Code Online (Sandbox Code Playgroud)

它显示为任何或我有此打字稿错误:

您指的是 'typeof CustomTheme' 吗?

我的问题是使用 Material UI 5.0 和 typescript 实现自定义主题的正确方法是什么

包.json

    // other dependencies
    "@emotion/react": "^11.4.1",
    "@emotion/styled": "^11.3.0",
    "@mui/icons-material": "^5.0.0",
    "@mui/material": "^5.0.0",
Run Code Online (Sandbox Code Playgroud)

Fre*_*yen -3

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

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

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

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