【问题标题】:Is there a way to add an icon when sort direction is null on Material UI's DataGrid headers?当 Material UI 的 DataGrid 标题上的排序方向为空时,有没有办法添加图标?
【发布时间】:2021-04-01 06:07:37
【问题描述】:

Material UI 的DataGrid's API 显示了如何在方向为升序时添加一个排序图标,在排序方向为降序时添加另一个图标。这些默认为向上箭头和向下箭头图标,可以通过道具轻松更改。当排序方向为null 时,我的设计还需要一个图标(即用户尚未单击该列标题,但上下箭头表示该列是可排序的)。

我尝试了几种解决方案,但对其中任何一种都不满意。我尝试在ColDef 中使用renderHeaderSortModel 更改时实现图标,但它看起来不够好,而且DataGrid 布局由于某种原因在SortModel 更改时变得混乱。

当没有定义排序方向时,有没有更好的方法来简单地在标题旁边添加一个可排序的图标?

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    Material-UI DataGrid 没有将图标设置为无排序状态的选项。为此,您需要亲自动手。

    我尝试在 ColDef 中使用 renderHeader 在 SortModel 更改时实现图标,但它看起来不够好

    为了复制内置的排序图标,您需要知道在排序模式下哪些组件会在列标题中呈现。看一下DataGrid源代码,可以看到:

    • GridColumnHeaderItem 中:如果您不提供renderHeader,它将改为呈现GridColumnHeaderTitle。所以我们需要使用那个组件来渲染头部。

    • GridColumnHeaderSortIcon 中:该组件用于呈现排序图标,图标被包裹在IconButton 中,small 大小本身被包裹在容器中。确保在呈现自己的标题图标时复制该代码。

    将它们放在一起,我们将得到如下所示:

    import { GridColumnHeaderTitle } from "@material-ui/x-grid";
    
    {
      field: "firstName",
      headerName: "First name",
      width: 130,
      renderHeader: (params) => {
        const { field, api, colDef } = params;
        const sort = api.state.sorting.sortModel.filter(
          (s) => s.field === field
        )?.[0]?.sort;
        const isSorting = Boolean(sort);
    
        return (
          <>
            <GridColumnHeaderTitle
              label={colDef.headerName || colDef.field}
              description={colDef.description}
              columnWidth={colDef.width}
            />
            {!isSorting && (
              <div className="MuiDataGrid-iconButtonContainer">
                <IconButton size="small">
                  <ClearIcon className="MuiDataGrid-sortIcon" />
                </IconButton>
              </div>
            )}
          </>
        );
      }
    },
    

    现场演示

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-24
      • 1970-01-01
      相关资源
      最近更新 更多