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

React中MUI AppBar边缘按钮布局:能否不使用Grid实现?

在MUI AppBar中实现左右按钮布局(无需Grid组件)

完全可以不用Grid组件,利用MUI的Toolbar(本身是flex容器)和Box组件的flex布局就能轻松实现需求,具体实现如下:

核心思路

  1. 用AppBar包裹Toolbar,Toolbar默认是display: flex布局,通过sx属性设置justifyContent: space-between,让左右内容分别靠向两侧。
  2. 左侧用一个Box容器包裹两个按钮,给这个Box设置marginLeft: 10px来保证与左边缘的间距。
  3. 右侧直接放置单个按钮,无需额外容器(也可以用Box包裹,看个人习惯)。

完整代码示例

import React from 'react';
import { AppBar, Toolbar, Box, Button } from '@mui/material';

const CustomAppBar = () => {
  return (
    <AppBar position="static">
      <Toolbar sx={{ justifyContent: 'space-between' }}>
        {/* 左侧按钮组 */}
        <Box sx={{ ml: 10 }}>
          <Button color="inherit">按钮1</Button>
          <Button color="inherit">按钮2</Button>
        </Box>
        {/* 右侧按钮 */}
        <Button color="inherit">右侧按钮</Button>
      </Toolbar>
    </AppBar>
  );
};

export default CustomAppBar;

细节说明

  • sx={{ ml: 10 }}中的ml是MUI的间距简写,对应margin-left: 10px;如果用主题间距单位,ml: 2对应8px,可根据需求调整数值。
  • 若要给左侧按钮之间添加间距,可给按钮加上mx: 1这类样式,比如<Button color="inherit" sx={{ mx: 1 }}>按钮1</Button>。
  • Toolbar的justifyContent: space-between会自动把左侧Box和右侧按钮分别推到左右两端,无需额外定位。

内容的提问来源于stack exchange,提问作者EaswarD Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:42:03