Material UI 数据网格:有没有办法右对齐整个列?

问题描述 投票:0回答:2

我是 Material UI 新手,一直在尝试解决这个问题。

在 Material UI 中,有没有办法在数据网格中放置两列,一列左对齐,一列右对齐?到目前为止,我已经能够左右对齐标题,但我这样做的方式似乎将单元格留在了后面。

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

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

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;

如您所见,我的方法是将每列宽度设置为 50%。这实际上适用于标题,但格式不会延续到单元格。我有办法做到这一点吗?

沙箱:https://codesandbox.io/s/material-demo-forked-gcvi8?file=/demo.js

javascript html css reactjs material-ui
2个回答
1
投票

您可以使用自定义 CSS,以便将级联列的宽度增加到 100%。

.MuiDataGrid-renderingZone, .MuiDataGrid-root .MuiDataGrid-row {
  width: 100% !important;
}

我使用

!important
来覆盖 ReactJS 添加的内联 CSS。如果您参考 ReactJS 文档,可能会有内置的解决方案。

Codesandbox 演示: https://j0geb.csb.app/


0
投票

我最近也遇到了这个问题。它建立在原始代码之上。它只是在列定义上提供了一个

flex: 1
属性来拉伸列以填充宽度。

const columns = [
    { field: 'id', headerName: 'Column 1'},
    { field: 'data', headerName: 'Column 2', flex: 1, align: "right", headerAlign: "right" },
  ];
© www.soinside.com 2019 - 2024. All rights reserved.