如何对material-ui DataGrid 中的列进行自动换行?

Raf*_*ias 4 node.js typescript reactjs material-ui tailwind-css

我正在尝试从material-ui 中自动换行DataGrid 的列标题标题,但没有成功。

我尝试过使用 sx, style,但它不起作用。也尝试过这个:

const StyledDataGridtwo = styled(DataGrid)<DataGridProps>(({ theme }) => ({
root: {
    '& .MuiDataGrid-columnHeaderTitle': {
        wordWrap: 'break-word'
    }
}}))
<StyledDataGridtwo rows={rows} columns={columns} />
Run Code Online (Sandbox Code Playgroud)

但这不起作用。我想做一些像excel那样的东西。有什么办法可以做到这一点吗?

Rya*_*ell 7

需要重写的主要属性是空白CSS 属性(而不是word-wrap属性)。然而line-height也需要调整,否则它会以一种非常丑陋的方式换行(每行文本 56px)。如果您的标题有可能换行超过 3 行,那么您还需要覆盖标题的一些高度 CSS。

这是一个工作示例:

import * as React from "react";
import { DataGrid } from "@mui/x-data-grid";

const rows = [
  {
    id: 1,
    username: "@MUI",
    age: 20
  }
];

export default function HeaderColumnsGrid() {
  return (
    <div style={{ height: 250, width: "100%" }}>
      <DataGrid
        sx={{
          "& .MuiDataGrid-columnHeaderTitle": {
            whiteSpace: "normal",
            lineHeight: "normal"
          },
          "& .MuiDataGrid-columnHeader": {
            // Forced to use important since overriding inline styles
            height: "unset !important"
          },
          "& .MuiDataGrid-columnHeaders": {
            // Forced to use important since overriding inline styles
            maxHeight: "168px !important"
          }
        }}
        columns={[
          {
            field: "username",
            headerName: "Really long header name",
            description:
              "The identification used by the person with access to the online service."
          },
          { field: "age", headerName: "Another really long header name" }
        ]}
        rows={rows}
      />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

编辑换行标题

我还建议对存在的问题进行投票:https ://github.com/mui/mui-x/issues/898 。