如何传递MUI5提供的默认主题并为MUI5中的任何组件创建样式?

问题描述 投票:0回答:1
import { styled } from "@mui/system";
import { CardTravel, Home, People } from "@mui/icons-material";
import { Box, Container, Typography } from "@mui/material";
import React from "react";



const BoxContainer = styled(Box)(({ theme }) => ({
  display: "flex",
  marginBottom: theme.spacing(4),
  [theme.breakpoints.up("sm")]: {
    marginBottom: theme.spacing(3),
    cursor: "pointer",
  },
}));

const TextContainer = styled(Typography)(({ theme }) => ({
  [theme.breakpoints.down("sm")]: {
    display: "none",
  },
}));

const styles = {   //here how can I use theme here  and pass it
  iconStyles: {
    marginRight: 2,
[theme.breakpoints.up("sm"): { //so I can use here for breakpoints or anything
display: "none", 
  },
};

const Leftbar = () => {
  return (
    <Container
      sx={{
        paddingTop: 2,
        height: "100vh",
        bgcolor: { sm: "white", xs: "primary.main" },
        color: { sm: "#555", xs: "white" },
        border: { sm: "1px solid #ece7e7" },
      }}
    >
      <BoxContainer>
        <Home sx={styles.iconStyles} />
        <TextContainer>HomePage</TextContainer>
      </BoxContainer>
      <BoxContainer>
        <People sx={styles.iconStyles} />
        <TextContainer>HomePage</TextContainer>
      </BoxContainer>
      <BoxContainer>
        <CardTravel sx={styles.iconStyles} />
        <TextContainer>HomePage</TextContainer>
      </BoxContainer>
      <BoxContainer>
        <Home sx={styles.iconStyles} />
        <TextContainer>HomePage</TextContainer>
      </BoxContainer>
    </Container>
  );
};

export default Leftbar;

在这里,在我的代码中,所有图标都不同,但它们的 css 属性是相同的。我不能使用 styled() 因为它们都是不同的图标。我正在尝试定义自定义样式,并尝试通过定义为 styles.iconStyles 来使用“sx”传递它。我如何在该代码中使用主题?

reactjs next.js material-ui theming
1个回答
1
投票

index.js
中,导入
createTheme
ThemeProvider
。 您可以使用
createTheme
创建自定义主题 并将
ThemeProvider
括在
<App/>

import { createTheme, ThemeProvider } from "@mui/material/styles";

const theme = createTheme({
  palette: {
    primary: {
      main: orange[500]
    },
    secondary: {
      main: red[500]
    }
  }
});

<ThemeProvider theme={theme}>
      <App />
</ThemeProvider>

创建您自己的组件并从您声明的主题中获取颜色,如下所示

const SearchDiv = styled("div", {
  shouldForwardProp: (props) => true
})(({ theme, open }) => ({
  display: "flex",
  alignItems: "center",
  backgroundColor: theme.palette.secondary.main,
  width: "50%",
  [theme.breakpoints.down("sm")]: {
    display: open ? "flex" : "none"
  }
}));

在此处查看代码和框:参见此

© www.soinside.com 2019 - 2024. All rights reserved.