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”传递它。我如何在该代码中使用主题?
在
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"
}
}));
在此处查看代码和框:参见此