You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React MUI Box中基于xs、sm网格类显示不同图片

React MUI Box 多断点背景图适配方案

直接在sx属性中实现断点切换

MUI的sx属性支持和direction={{ xs: 'column', sm: 'row' }}完全一致的断点对象语法,直接给backgroundImage设置断点对应的图片路径即可,同时可同步适配宽度解决移动端尺寸问题:

<Box
  sx={{
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
    height: '100%',
    // 适配宽度:移动端占满,桌面端保持70%
    width: { xs: '100%', sm: '70%' },
    // 按断点指定不同背景图
    backgroundImage: {
      xs: `url("./letter-mobile.png")`, // 移动端适配图片
      sm: `url("./letter2.png")`        // 桌面端图片
    }
  }}
>
  <div>
    <TypeAnimation sequence={[...]} />
  </div>
</Box>

基于主题统一管理适配图片

如果项目中多处需要用到这套适配规则,可以把图片路径配置到MUI主题中,方便统一维护:

1. 配置自定义主题

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

const customTheme = createTheme({
  // 自定义背景图断点配置
  customBackgrounds: {
    letter: {
      xs: `url("./letter-mobile.png")`,
      sm: `url("./letter2.png")`
    }
  },
  // 全局配置Box基础样式(可选)
  components: {
    MuiBox: {
      styleOverrides: {
        root: {
          backgroundRepeat: 'no-repeat',
          backgroundSize: 'cover',
          height: '100%',
          width: { xs: '100%', sm: '70%' }
        }
      }
    }
  }
});

2. 在组件中调用主题配置

<ThemeProvider theme={customTheme}>
  <Box
    sx={(theme) => ({
      // 从主题中读取断点对应的图片路径
      backgroundImage: theme.customBackgrounds.letter
    })}
  >
    <div>
      <TypeAnimation sequence={[...]} />
    </div>
  </Box>
</ThemeProvider>

补充方案:不换图仅调整显示效果

如果不想更换图片,仅解决移动端图片尺寸过大的问题,可单独给移动端调整backgroundSize属性:

sx={{
  // ...其他样式
  backgroundSize: { xs: 'contain', sm: 'cover' }
}}

内容的提问来源于stack exchange,提问作者Kris Swat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:37:24