React中MUI AppBar边缘按钮布局:能否不使用Grid实现?
在MUI AppBar中实现左右按钮布局(无需Grid组件)
完全可以不用Grid组件,利用MUI的Toolbar(本身是flex容器)和Box组件的flex布局就能轻松实现需求,具体实现如下:
核心思路
- 用
AppBar包裹Toolbar,Toolbar默认是display: flex布局,通过sx属性设置justifyContent: space-between,让左右内容分别靠向两侧。 - 左侧用一个
Box容器包裹两个按钮,给这个Box设置marginLeft: 10px来保证与左边缘的间距。 - 右侧直接放置单个按钮,无需额外容器(也可以用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
相关产品推荐
相关产品推荐

