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

如何在React.js中使用MUI库调整导航项按钮位置并添加间距

在React MUI中为导航栏按钮添加间距的解决方案

问题描述

我需要在React.js中使用MUI库调整导航栏按钮的位置,使按钮之间产生间距。当前实现代码如下:

import * as React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import Drawer from '@mui/material/Drawer';
import IconButton from '@mui/material/IconButton';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import MenuIcon from '@mui/icons-material/Menu';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import EngineeringIcon from '@mui/icons-material/Engineering';

interface Props {
  /**
   * 文档注入的属性,用于在iframe中运行,项目中无需使用
   */
  window?: () => Window;
}

const drawerWidth = 240;
const navItems = ['首页', '关于我', '联系我'];

export default function DrawerAppBar(props: Props) {
  const { window } = props;
  const [mobileOpen, setMobileOpen] = React.useState(false);

  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };

  const drawer = (
    <Box onClick={handleDrawerToggle} sx={{ textAlign: 'center'}} >
      <Typography variant="h6" sx={{ my: 2 }} >
        MUI
      </Typography>
      <Divider />
      <List>
        {navItems.map((item) => (
          <ListItem key={item} disablePadding>
            <ListItemButton sx={{ textAlign: 'center' }}>
              <ListItemText primary={item} />
            </ListItemButton>
          </ListItem>
        ))}
      </List>
    </Box>
  );

  const container = window !== undefined ? () => window().document.body : undefined;

  return (
    <Box sx={{ display: 'flex' }}>
      <AppBar component="nav" style={{ background:'#5689c0' }} >
        <Toolbar variant="dense">
          <IconButton
            color="inherit"
            aria-label="打开侧边栏"
            edge="start"
            onClick={handleDrawerToggle}
            sx={{ mr: 2, display: { sm: 'none' } }}
          >
            <MenuIcon />
          </IconButton>
          <Typography
            variant="h6"
            component="div"
            sx={{ flexGrow: 1, display: { xs: 'none', sm: 'block' } }}
          >
           <EngineeringIcon fontSize='large' />
          </Typography>
          <Box sx={{ display: { xs: 'none', sm: 'block' } }}>
            {navItems.map((item) => (
              <Button key={item} sx={{ color: '#fff' }}>
                {item}
              </Button>
            ))}
          </Box>
        </Toolbar>
      </AppBar>
      <Box component="nav">
        <Drawer
          container={container}
          variant="temporary"
          open={mobileOpen}
          onClose={handleDrawerToggle}
          ModalProps={{
            keepMounted: true, // 提升移动端打开性能
          }}
          sx={{
            display: { xs: 'block', sm: 'none' },
            '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
          }}
        >
          {drawer}
        </Drawer>
      </Box>
      <Box component="main" sx={{ p: 0 }}>
        <Toolbar />
      </Box>
    </Box>
  );
}

两种实现按钮间距的方法

方法一:使用Flex布局的gap属性(推荐)

直接给包裹按钮的外层Box添加gap样式,自动在按钮之间生成均匀间距,代码简洁易维护:

修改后的Box代码:

<Box sx={{ display: { xs: 'none', sm: 'block' }, gap: 2 }}>
  {navItems.map((item) => (
    <Button key={item} sx={{ color: '#fff' }}>
      {item}
    </Button>
  ))}
</Box>

gap: 2对应MUI的间距单位(1单位=8px),可根据需求调整数值,比如gap: 3对应24px间距。

方法二:为每个按钮添加条件性外边距

如果需要精细控制(比如不给最后一个按钮加右边距),可以给Button添加条件性的margin-right:

修改后的按钮渲染代码:

<Box sx={{ display: { xs: 'none', sm: 'block' } }}>
  {navItems.map((item, index) => (
    <Button 
      key={item} 
      sx={{ 
        color: '#fff', 
        // 仅给非最后一个按钮添加右边距
        mr: index !== navItems.length - 1 ? 2 : 0 
      }}
    >
      {item}
    </Button>
  ))}
</Box>

内容的提问来源于stack exchange,提问作者Besher Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:30:25