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

如何在MUI5导航栏中使用breakpoints实现响应式适配

MUI breakpoints 实现响应式导航栏修复方案

你代码的核心问题是sx属性的传值格式不匹配:你定义的styles函数返回的对象多了一层root嵌套,而sx属性直接接收样式对象本身,不需要外层的root键。

修复方案1:调整样式结构适配sx属性

直接移除外层的root嵌套即可正常生效,完整代码如下:

import * as React from 'react';
import Typography from '@mui/material/Typography';
import { green } from '@mui/material/colors';
import { AppBar } from '@mui/material';

// 去掉外层root嵌套,直接返回样式对象
const styles = (theme) => ({
  padding: theme.spacing(1),
  [theme.breakpoints.down('md')]: {
    backgroundColor: theme.palette.secondary.main,
  },
  [theme.breakpoints.up('md')]: {
    backgroundColor: theme.palette.primary.main,
  },
  [theme.breakpoints.up('lg')]: {
    backgroundColor: green[500],
  },
});

export default function MediaQuery() {
  return (
    <AppBar sx={styles}>
      <Typography>red</Typography>
      <Typography>blue</Typography>
      <Typography>yellow</Typography>
    </AppBar>
  );
}

修复方案2:用styled高阶组件实现(可复用你已引入的styled依赖)

如果你偏好分离样式组件的写法,可以用styled包裹AppBar实现,完整代码如下:

import * as React from 'react';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import { green } from '@mui/material/colors';
import AppBar from '@mui/material/AppBar';

// 用styled包裹AppBar传入样式配置
const StyledAppBar = styled(AppBar)((theme) => ({
  padding: theme.spacing(1),
  [theme.breakpoints.down('md')]: {
    backgroundColor: theme.palette.secondary.main,
  },
  [theme.breakpoints.up('md')]: {
    backgroundColor: theme.palette.primary.main,
  },
  [theme.breakpoints.up('lg')]: {
    backgroundColor: green[500],
  },
}));

export default function MediaQuery() {
  return (
    <StyledAppBar>
      <Typography>red</Typography>
      <Typography>blue</Typography>
      <Typography>yellow</Typography>
    </StyledAppBar>
  );
}

效果说明

修改后断点触发逻辑和预期一致:

  • 屏幕宽度小于md(默认900px):导航栏背景为主题secondary色
  • 屏幕宽度在md到lg之间(默认900px~1199px):导航栏背景为主题primary色
  • 屏幕宽度大于等于lg(默认1200px):导航栏背景为绿色#4caf50

内容的提问来源于stack exchange,提问作者victor tonderai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:06:10