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

Material UI Data Grid整列右对齐及多列分别设置对齐方式实现方法

问题根因

你当前的写法不生效有两个核心原因:

  • @material-ui/data-grid的列配置width属性仅支持数值类型的像素值,你传入字符串格式的"50%"会导致列宽计算异常,直接影响单元格对齐配置的生效。
  • 低于v4.0.0的@material-ui/data-grid版本存在单元格align属性不生效的已知bug,可先升级到稳定的v4及以上版本排查版本问题。

解决方案

将列配置中的width: "50%"替换为flex: 1即可。flex属性会按照权重自动分配DataGrid容器的剩余宽度,两列都设置flex: 1就会自动各占50%宽度,同时你配置的align属性会同步在表头和单元格生效。

修改后的完整代码如下:

import * as React from "react";
import { DataGrid } from '@material-ui/data-grid';

const columns = [
    { field: 'id', headerName: 'Column 1', align: "left", headerAlign: "left", flex: 1 },
    { field: 'data', headerName: 'Column 2', align: "right", headerAlign: "right", flex: 1 },
  ];

const rows = [
  { id: 1, data: 'asdfasdf'},
  { id: 2, data: '12951d'}, ];


function DataTable () {

    return (
        <div style={{ height: 400, width: '100%' }}>
          <DataGrid  rows={rows} columns={columns} pageSize={5} />
        </div>
      );
    
}

export default DataTable;

如果需要固定列宽,直接给width传入像素数值即可,比如width: 200,同样可以正常触发对齐配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 03:06:05