如何利用MUI断点根据屏幕尺寸切换不同规格图片?
MUI断点实现不同屏幕尺寸切换对应图片
实现思路
利用MUI的useMediaQuery+useTheme钩子,根据屏幕断点动态切换图片的src、width和height;如果默认断点不符合你的屏幕尺寸,可自定义断点精准匹配1280×832和1920×1080规格。
步骤1:基础实现(使用默认断点)
假设你的EmptyState组件初始代码如下,直接修改适配:
import React from 'react'; import { Box, Typography, useTheme, useMediaQuery } from '@mui/material'; const EmptyState = () => { const theme = useTheme(); // 判断是否为1536px及以上屏幕(MUI默认xl断点),匹配1920×1080规格 const isLargeScreen = useMediaQuery(theme.breakpoints.up('xl')); // 定义两种图片规格参数 const desktopXL = { src: '/path/to/empty-state-xl.png', // 333px宽 × 306px高的图片 width: '333px', height: '306px' }; const desktopLG = { src: '/path/to/empty-state-lg.png', // 285px×285px的图片 width: '285px', height: '285px' }; // 根据屏幕尺寸选择对应图片 const currentImage = isLargeScreen ? desktopXL : desktopLG; return ( <Box textAlign="center" py={4}> <img src={currentImage.src} alt="Empty state" style={{ width: currentImage.width, height: currentImage.height }} /> <Typography variant="body1">暂无数据</Typography> </Box> ); }; export default EmptyState;
步骤2:自定义断点(精准匹配你的屏幕尺寸)
如果MUI默认断点不符合需求,可自定义规则匹配你的目标屏幕:
- 在根组件或主题配置文件中创建自定义主题:
import { createTheme, ThemeProvider } from '@mui/material/styles'; // 自定义断点,精准对应你的屏幕尺寸 const customTheme = createTheme({ breakpoints: { values: { xs: 0, sm: 600, md: 900, lg: 1280, // 匹配1280×832屏幕 xl: 1920 // 匹配1920×1080屏幕 } } }); // 用自定义主题包裹应用 function App() { return ( <ThemeProvider theme={customTheme}> <EmptyState /> </ThemeProvider> ); }
- 修改
EmptyState中的判断逻辑,使用自定义断点:
// 替换原判断逻辑,适配自定义断点 const isXL = useMediaQuery(theme.breakpoints.up('xl')); const currentImage = isXL ? desktopXL : desktopLG;
关键说明
useTheme:获取MUI主题对象,包含断点配置信息useMediaQuery:监听当前屏幕是否符合指定断点条件,返回布尔值- 图片路径需根据项目结构调整,确保资源可正常访问
- 若需要平滑尺寸过渡,可给
img添加transition: all 0.3s ease样式
内容的提问来源于stack exchange,提问作者mariadev
相关产品推荐
相关产品推荐

