繁体   English   中英

带有情感的 MUI v5 主题/mui

[英]MUI v5 theming with emotion/mui

我已将 MUI 从 v4 升级到 v5。 但是,我现在很难理解主题如何与可用的不同主题解决方案配合使用。 我真的不明白在哪里使用 MUI 主题/样式组件以及何时使用情感组件。

在新组件中,我使用sx属性来应用样式,但是我有相当多的组件仍在使用createStyles / useStyles函数。

我目前有以下设置:

import {
  ThemeProvider as MuiThemeProvider,
  Theme,
  StyledEngineProvider,
  createTheme,
} from "@mui/material/styles";
import { ThemeProvider } from "@emotion/react";

declare module "@mui/material/styles" {
  interface Theme {
    mycompany: {
      primary: string;
    };
  }
  // allow configuration using `createTheme`
  interface ThemeOptions {
    mycompany: {
      primary: string;
    };
  }
}

declare module "@mui/styles/defaultTheme" {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface
  interface DefaultTheme extends Theme {}
}

const theme = createTheme({
  mycompany: {
    primary: "#003366",
  },
});

const App = () => {
  return (
    <StyledEngineProvider injectFirst>
      <MuiThemeProvider theme={theme}>
        <ThemeProvider theme={theme}>
          <Router>
            ...
          </Router>
        </ThemeProvider>
      </MuiThemeProvider>
    </StyledEngineProvider>

我现在如何使用theme.mycompany.primary值? 我试过这样:

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

const MyComponent = () => {
    const theme = useTheme();

    return (
      <Box sx={{backgroundColor: theme.mycompany.primary}}>
        ...
      </Box>

是否有在不同文件中的多个组件中使用带有打字稿的新样式解决方案的项目示例?

docsuseTheme应该从@mui/material/styles导入。

如果您使用sx道具,您应该将您的自定义颜色代码放在调色板中,如下所示:

const theme = createTheme({
  palette: {
    mycompany: {
      primary: "#003366"
    }
  },
});

并在您的组件中引用颜色:

<Box sx={{ width: 30, height: 30, bgcolor: "mycompany.primary" }} />

如果您使用styled您可以添加一个回调,其中theme是第一个参数的属性:

const MyComponent = styled(Box)(({ theme }) => {
  return {
    backgroundColor: theme.palette.mycompany.primary,
    width: 30,
    height: 30
  };
});

现场演示

代码沙盒演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM