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

MUI DataGrid报useResizeContainer错误:父元素宽度为空问题

解决MUI DataGrid父元素宽度为空的报错问题

问题分析

你已通过列宽总和设置容器maxWidth,但仍触发useResizeContainer警告,核心原因:

  • maxWidth是最大宽度限制,并非固定宽度值,DataGrid初始化时无法从父容器获取明确的固有宽度,因此判定父元素宽度为空。
  • 代码中错误重复传递{...rows}给DataGrid,会干扰组件正常的props解析逻辑。

解决步骤

  1. 将容器maxWidth改为固定width:确保父容器在初始化阶段就有明确宽度,让DataGrid能正确读取尺寸。
  2. 移除重复的{...rows}传递:rows已通过独立props传入,重复传递会引发不必要的渲染异常。
  3. 可选:直接给DataGrid设置width:进一步明确表格自身宽度,避免宽度计算偏差。

修改后的代码

const columns: GridColDef[] = [
    { field: 'Job id', headerName: 'Job id', colId:'Job id', width: 150 , sortable:true, editable:false, type:'text', align:'center',headerAlign: 'center'},
    { field: 'Name', headerName: 'Name', colId:'Name', width: 80, sortable:true, editable:false, type:'text', align:'center',headerAlign: 'center'},
    { field: 'User', headerName: 'User', colId:'User', width: 80, sortable:true, editable:false, type:'text', align:'center',headerAlign: 'center'},
    { field: 'Time Use', headerName: 'Time Use', colId:'Time Use', width: 90, sortable:true, editable:false, type:'text', align:'center',headerAlign: 'center'},
    { field: 'S', headerName: 'S', colId:'S', width: 50, sortable:true, editable:false, type:'text', align:'center',headerAlign: 'center'},
    { field: 'Queue', headerName: 'Queue', colId:'Queue', width: 80, sortable:true, editable:false, type:'text', align:'center',headerAlign: 'center'},
  ]

const columnWidths = columns.reduce((acc, column) => acc + column.width, 0);
const gridTotalWidth = columnWidths + 10; // 额外预留10px宽度

const containerStyle = {
  margin: '10px auto',
  width: gridTotalWidth, // 改用固定width替代maxWidth
};

return (
    <div style={{ marginTop: 10, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <div style={containerStyle}>
        <DataGrid
            columnBuffer={6}
            disableVirtualization
            density='compact'
            rows={rows}
            columns={columns}
            getRowHeight={({ id, densityFactor }) => 30 * densityFactor}           
            disableSelectionOnClick   
            hideFooter={true}
            rowBorder={false}
            disableColumnFilter={true}
            disableColumnMenu={true}
            width={gridTotalWidth} // 可选:直接给表格指定宽度
        />
        </div>
    </div>
)

响应式场景补充

如果需要在小屏幕下自适应宽度,可以给容器同时设置固定宽度和最大宽度限制:

const containerStyle = {
  margin: '10px auto',
  width: gridTotalWidth,
  maxWidth: '100%',
};

这样既保证初始化时的明确宽度,又能在屏幕尺寸不足时自适应容器宽度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:50:24