如何在MUI断点中修改侧边栏图标尺寸?
MUI React侧边栏图标尺寸修改问题
问题场景
我基于MUI编写了React侧边栏,尝试在sm断点下修改图标尺寸,但给Icon styled组件设置fontSize属性始终不生效。
完整代码
import { Container } from "@mui/material"; import * as React from "react"; import { Home } from "@mui/icons-material"; import PersonIcon from "@mui/icons-material/Person"; import FormatListBulletedIcon from "@mui/icons-material/FormatListBulleted"; import CameraAltIcon from "@mui/icons-material/CameraAlt"; import OndemandVideoIcon from "@mui/icons-material/OndemandVideo"; import PhoneAndroidIcon from "@mui/icons-material/PhoneAndroid"; import FeaturedPlayListIcon from "@mui/icons-material/FeaturedPlayList"; import StorefrontIcon from "@mui/icons-material/Storefront"; import SettingsIcon from "@mui/icons-material/Settings"; import LogoutIcon from "@mui/icons-material/Logout"; import Typography from "@mui/material/Typography"; import { styled } from "@mui/material/styles"; const StyledContainer = styled("div")(({ theme }) => ({ paddingTop: theme.spacing(10), backgroundColor: theme.palette.primary.main, height: "100vh", color: "white", [theme.breakpoints.up("sm")]: { backgroundColor: "white", color: "#555", border: "1px solid #ece7e7", }, })); const Item = styled("div")(({ theme }) => ({ display: "flex", alignItems: "center", marginBottom: theme.spacing(4), [theme.breakpoints.up("sm")]: { marginBottom: theme.spacing(3), cursor: "Pointer", }, })); const Icon = styled("div")(({ theme }) => ({ marginRight: theme.spacing(1), [theme.breakpoints.up("sm")]: { //I need to change the Icon size //fontSize:"18px" but this not working }, })); const Text = styled("div")(({ theme }) => ({ fontWeight: 500, fontSize: "300px", [theme.breakpoints.down("sm")]: { display: "none", }, })); function Leftbar() { return ( <StyledContainer> <Container> <div> <Item> <Icon> <Home /> </Icon> <Text> <Typography>Homepage</Typography> </Text> </Item> </div> <div> <Item> <Icon> <PersonIcon /> </Icon> <Text> <Typography>Friends</Typography> </Text> </Item> </div> </Container> </StyledContainer> ); } export default Leftbar;
页面效果

问题原因
MUI图标最终渲染为<svg>元素,它的尺寸由自身的fontSize样式控制。之前给父级div设置fontSize,无法覆盖图标自身的默认样式,也不会被svg元素继承,所以设置不生效。
解决方案
方案1:直接选中svg元素设置样式
修改Icon styled组件,通过CSS选择器直接定位到内部的svg元素:
const Icon = styled("div")(({ theme }) => ({ marginRight: theme.spacing(1), [theme.breakpoints.up("sm")]: { '& svg': { fontSize: '18px', // 这里设置目标尺寸 }, }, }));
方案2:使用MUI的Icon组件包裹图标
改用@mui/material/Icon作为图标容器,直接通过styled组件控制尺寸:
- 先导入Icon组件:
import Icon from "@mui/material/Icon";
- 创建StyledIcon组件:
const StyledIcon = styled(Icon)(({ theme }) => ({ marginRight: theme.spacing(1), [theme.breakpoints.up("sm")]: { fontSize: '18px', }, }));
- 在侧边栏中使用:
<StyledIcon> <Home /> </StyledIcon>
方案3:直接给图标添加响应式sx属性
在图标组件上通过sx属性直接写断点样式,无需修改styled组件:
<Icon> <Home sx={{ [theme.breakpoints.up('sm')]: { fontSize: '18px' } }} /> </Icon>
内容的提问来源于stack exchange,提问作者ShewaniPerera
相关产品推荐
相关产品推荐

