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

Material UI中如何为每个Grid Item添加右侧编辑与删除按钮?

解决Material UI Grid Item旁添加编辑/删除按钮的布局问题

直接给你调整后的代码,核心是用flex布局让内容区和按钮区在Grid Item内横向排列,同时保留Grid的响应式特性:

<Grid container width="100%" spacing={2}> {/* 用spacing控制Grid Item之间的间距,替代固定width */}
  {ingredientsList.map((item) => (
    <Grid item xs={12} md={5} key={item.id} sx={{ 
      display: 'flex', 
      alignItems: 'center', 
      gap: 2, // 内容和按钮之间的间距
    }}>
      {/* 内容区:占满剩余空间 */}
      <IngredientItem sx={{ flex: 1 }}>
        <IngredientName>{item.name}</IngredientName>
        <Box display="flex" flexDirection="row" alignItems="end">
          <Quantity>1</Quantity>
          <Unit>{item.unit}</Unit>
        </Box>
      </IngredientItem>
      
      {/* 按钮区:横向排列 */}
      <Box display="flex" gap={1}>
        <EditButton onClick={() => console.log("Edit clicked", item.id)}>
          <Edit />
        </EditButton>
        <DeleteButton onClick={() => handleRemoveIngredient(item.id)}>
          <Delete />
        </DeleteButton>
      </Box>
    </Grid>
  ))}
</Grid>

关键调整说明:

  • 去掉了Grid Item上的固定width:700px,改用Grid的xs/md响应式断点控制宽度,避免破坏Grid的流式布局
  • 给Grid Item添加display:flex和alignItems:center,让内容和按钮垂直居中对齐
  • 给IngredientItem设置flex:1,让它占满Grid Item内的剩余空间,按钮区只占自身宽度
  • 用gap属性控制元素间的间距,替代手动margin,更符合Material UI的设计规范
  • 把按钮从IngredientItem内部移出,单独放在一个flex Box里,避免打乱内容区的布局

如果你的EditButton/DeleteButton是自定义组件,确保它们的样式不会强制占满宽度(比如去掉width:100%之类的设置),否则按钮会撑大容器。

内容的提问来源于stack exchange,提问作者Asfand Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:10:06