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

如何让React MUI DataGrid根据标签列内容动态调整行高?

解决MUI DataGrid标签列动态行高问题

1. 让标签自动换行

先修改标签列的渲染逻辑,给Stack添加wrap="wrap"属性,确保标签数量超出列宽时自动换行,避免内容被截断:

const columns = [{
  field: "tags",
  headerName: "Tags",
  renderCell: (params) => (
    <Stack direction="row" spacing={0.25} wrap="wrap">
      {params.row.tags.map((tag, index) => (
        <Chip key={index} label={tag} />
      ))}
    </Stack>
  ),
  editable: true,
  flex: 2.5,
}];

2. 配置动态行高

在DataGrid组件中添加getRowHeight属性,根据每行的标签数量动态计算行高。默认Chip高度约32px,加上间距和行内边距,按每行40px的基准计算:

<DataGrid
  rows={yourRowData}
  columns={columns}
  // 移除固定行高设置(如果之前有配置)
  getRowHeight={(params) => {
    // 假设每行最多显示3个标签,可根据实际列宽调整这个数值
    const tagsPerRow = 3;
    const rowCount = Math.ceil(params.row.tags.length / tagsPerRow);
    // 基础行高40px,每多一行追加40px
    return 40 * rowCount;
  }}
/>

更精准的行高计算(可选)

如果标签长度差异较大,固定数量估算不够准确,可以通过计算标签总宽度和列宽来动态算出行数:

// 估算单个标签的宽度
const calculateTagWidth = (tag) => {
  // 字符宽度按8px计算,加上Chip的内边距24px
  return tag.length * 8 + 24;
};

// 在getRowHeight中使用
getRowHeight={(params) => {
  // 获取标签列的实际宽度,默认300px
  const columnWidth = params.columns.find(col => col.field === 'tags').width || 300;
  const totalTagWidth = params.row.tags.reduce((sum, tag) => sum + calculateTagWidth(tag), 0);
  // 最少显示1行,超过列宽则自动计算行数
  const rowCount = Math.max(1, Math.ceil(totalTagWidth / columnWidth));
  return 40 * rowCount;
}}

注意事项

  • 不要给DataGrid设置固定rowHeight属性,否则会覆盖动态计算结果。
  • 如果使用了自定义样式的Chip,需要根据实际高度调整基准行高的数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:55:01