簡體   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