首页 > 解决方案 > 材质 UI 数据网格粘页眉

问题描述

是否可以使 Material UI Datagrid Header 具有粘性?似乎这可以通过 Material UI Tables 实现。我无法找到使用数据网格执行此操作的选项。

标签: datagridmaterial-ui

解决方案


如评论中所述,这是默认行为。然而,很少有错误可以阻止此默认功能。就我而言,这是我错过的财产: autoHeight={true},它应该是false或只是将其删除。

这是一个广泛的代码示例,下面是 SandBox 的链接:

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

export default function AdvanceTable() {
  
  const [pageSize, setPageSize] = React.useState(5);
  const [editRowsModel, setEditRowsModel] = React.useState({});

  const handleEditRowsModelChange = React.useCallback((model) => {
    // Set current edited cell
    setEditRowsModel(model);
  });

  return (
    <div>
      <div style={{ width: "100%", height: "80vh" }}>
        <DataGrid
          components={{
            Toolbar: GridToolbar
          }}
          rows={rows}
          columns={columns}
          disableSelectionOnClick
          checkboxSelection
          onEditRowsModelChange={handleEditRowsModelChange}
          pagination
          pageSize={pageSize}
          onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
          rowsPerPageOptions={[5, 10, 15]}
        />
      </div>
      <div style={{ marginBottom: 8 }}>
        <code>Edited table values: {JSON.stringify(editRowsModel)}</code>
      </div>
    </div>
  );
  
  // mock data:
  const columns = [
    { field: "id", headerName: "ID", width: 70 },
    {
      field: "firstName",
      headerName: "First name",
      editable: true,
      width: 180
    },
    { field: "lastName", headerName: "Last name", editable: true, width: 180 },
    {
      field: "age",
      headerName: "Age",
      type: "number",
      editable: true,
      width: 150
    }
  ];

  const rows = [
    { id: 1, lastName: "Snow", firstName: "Jon", age: 35 },
    { id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
    { id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
    { id: 4, lastName: "Stark", firstName: "Arya", age: 16 },
    { id: 5, lastName: "Targaryen", firstName: "Daenerys", age: null },
    { id: 6, lastName: "Melisandre", firstName: null, age: 150 },
    { id: 7, lastName: "Clifford", firstName: "Ferrara", age: 44 },
    { id: 8, lastName: "Frances", firstName: "Rossini", age: 36 },
    { id: 9, lastName: "Roxie", firstName: "Harvey", age: 65 },
    { id: 41, lastName: "Stark", firstName: "Arya", age: 16 },
    { id: 51, lastName: "Targaryen", firstName: "Daenerys", age: null },
    { id: 61, lastName: "Melisandre", firstName: null, age: 150 },
    { id: 71, lastName: "Clifford", firstName: "Ferrara", age: 44 },
    { id: 81, lastName: "Frances", firstName: "Rossini", age: 36 },
    { id: 91, lastName: "Roxie", firstName: "Harvey", age: 65 }
  ];
}

沙盒示例


推荐阅读