MUI DataGrid报useResizeContainer错误:父元素宽度为空问题
解决MUI DataGrid父元素宽度为空的报错问题
问题分析
你已通过列宽总和设置容器maxWidth,但仍触发useResizeContainer警告,核心原因:
maxWidth是最大宽度限制,并非固定宽度值,DataGrid初始化时无法从父容器获取明确的固有宽度,因此判定父元素宽度为空。- 代码中错误重复传递
{...rows}给DataGrid,会干扰组件正常的props解析逻辑。
解决步骤
- 将容器
maxWidth改为固定width:确保父容器在初始化阶段就有明确宽度,让DataGrid能正确读取尺寸。 - 移除重复的
{...rows}传递:rows已通过独立props传入,重复传递会引发不必要的渲染异常。 - 可选:直接给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
相关产品推荐
相关产品推荐

