简体   繁体   English

带有情感的 MUI v5 主题/mui

[英]MUI v5 theming with emotion/mui

I've upgraded MUI from v4 to v5.我已将 MUI 从 v4 升级到 v5。 However, I'm now having difficulties understanding how the theming works with the different theming solutions available.但是,我现在很难理解主题如何与可用的不同主题解决方案配合使用。 I don't really understand where to use the MUI theming/styling components and when to use the emotion ones.我真的不明白在哪里使用 MUI 主题/样式组件以及何时使用情感组件。

In new components, I'm using the sx prop to apply styling, however I have quite a lot of components still using the createStyles / useStyles functions.在新组件中,我使用sx属性来应用样式,但是我有相当多的组件仍在使用createStyles / useStyles函数。

I currently have the following setup:我目前有以下设置:

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>

How can I now use the theme.mycompany.primary value?我现在如何使用theme.mycompany.primary值? I've tried it like this:我试过这样:

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

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

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

Are there any examples of projects using the new styling solution with typescript across multiple components in different files?是否有在不同文件中的多个组件中使用带有打字稿的新样式解决方案的项目示例?

From the docs , useTheme should be imported from @mui/material/styles .docsuseTheme应该从@mui/material/styles导入。

If you use sx prop, you should put your custom color code in the palette like this:如果您使用sx道具,您应该将您的自定义颜色代码放在调色板中,如下所示:

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

And reference the color in your component:并在您的组件中引用颜色:

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

If you're using styled you can add a callback where the theme is a property of the first parram:如果您使用styled您可以添加一个回调,其中theme是第一个参数的属性:

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

Live Demo现场演示

代码沙盒演示

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

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