从MUI v4迁移至v5:媒体查询写法报错的正确实现方案
MUI v5中实现媒体查询的正确方式
你遇到的报错是因为MUI v5的样式对象不支持直接写原生CSS的@media字符串作为属性名,得用它内置的断点工具来处理。
下面是几种正确的实现方式:
1. 使用makeStyles配合主题断点(适合类组件或习惯hook写法的场景)
import { makeStyles } from '@mui/styles'; const useStyles = makeStyles((theme) => ({ iconFolder: { fontSize: 45, // 匹配max-width: 550px的屏幕 [theme.breakpoints.down(550)]: { fontSize: 30, }, }, }));
2. 使用styled组件(MUI v5推荐的方案)
如果用styled-components风格的写法,同样借助主题的断点方法:
import { styled } from '@mui/material/styles'; import FolderIcon from '@mui/icons-material/Folder'; const StyledFolderIcon = styled(FolderIcon)(({ theme }) => ({ fontSize: 45, [theme.breakpoints.down(550)]: { fontSize: 30, }, }));
3. 自定义断点(如果需要复用这个550px的断点)
先在主题里定义自定义断点,之后直接用名称调用:
import { createTheme, ThemeProvider } from '@mui/material/styles'; // 创建包含自定义断点的主题 const theme = createTheme({ breakpoints: { values: { xs: 0, sm: 600, md: 900, lg: 1200, xl: 1536, smallPhone: 550, // 自定义断点名称和值 }, }, }); // 在样式中使用自定义断点 [theme.breakpoints.down('smallPhone')]: { fontSize: 30, }
theme.breakpoints.down()方法会自动帮你生成对应的@media (max-width: XXXpx)媒体查询规则,完全符合MUI的样式系统规范,不会再出现报错。
内容的提问来源于stack exchange,提问作者Richardson
相关产品推荐
相关产品推荐

