MUI DataGrid 中的自动高度

Jon*_*man 6 css datagrid reactjs material-ui

我正在使用 MUIDataGrid组件,我希望的行为是:

  1. 当行数较少时,表的大小仅为这些行所需的大小。
  2. 当存在大量行时,超过当前视口可以容纳的行数(考虑到屏幕上的其他内容),表格会占用布局中的可用空间(考虑到其flex: 1),并且额外的行会在表格内滚动。

我可以实现这些行为中的每一项,但一次只能实现一个。

  1. 如果我使用autoHeight上的属性DataGrid,那么表将尽可能小。但它也会尽可能大,因此对于大量行,容器会滚动整个表,而不是在表内滚动行。

  2. 如果我不使用autoHeight,并将 包装DataGrid在容器中flex: 1,则表格将增长以填充可用空间,并且行将在表格内滚动。但是只有几行的表格也会增长以填充其容器,因此行下方有空白空间(页脚上方,“表格行:#”)

您可以在此屏幕截图中看到情况,显示完全相同的页面,但数据不同。

在此输入图像描述

我尝试过阳光下各种高度和弯曲的排列。例如:

  • 使用maxHeight( 和.MuiDataGrid-main { overflow: scroll; }) 设置 autoHeight 允许几行很小,而多行也不太小,但显然任何离散的maxHeight,无论是 px 还是 %,都不是flex我想要的合理布局。
  • 关闭 autoHeight(如场景 #2)并flex-grow: 0在表 ( ) 内的行容器上进行设置.MuiDataGrid-main只会使行消失,因为它们随后会缩小到高度 0。

组件的代码:

const S = {
  Wrapper: styled.div`
    width: 100%;
    display: flex;
    flex: 1;
    background: white;
    border: solid thick red;
  `,
  DataGrid: styled(DataGridPro)`
    && {
      .MuiDataGrid-main {
        //overflow: scroll;
        //flex-grow: 0;
      }
      background: lightgreen;
      font-size: 14px;
    }  
`,
};

type Props = {
  columns: ReadonlyColumns;
  rows: AnyObject[];
  filterModel?: GridFilterModel;
} & Omit<DataGridProps, 'columns'>;

const DataTable: React.FC<Props> = ({
  columns = [],
  rows = [],
  filterModel,
  className,
  ...props
}) => {
  const memoizedColumns = useMemo(
    () =>
      columns.map(col => ({
        headerClassName: 'columnHeader',
        flex: 1, // all columns expand to fill width
        ...col, // but could override that behavior
      })),
    [columns],
  );

  return (
    <S.Wrapper className={className}>
      <S.DataGrid
        // autoHeight
        rows={rows}
        columns={memoizedColumns}
        filterModel={filterModel}
        {...props}
      />
    </S.Wrapper>
  );
};

Run Code Online (Sandbox Code Playgroud)

小智 8

autoHeight使用和的组合pageSize将创建一个表,其高度仅与当前行数所需的大小相同,只要行数为<= pageSize。附加行将添加到新页面。

<DataGrid
    rows={rows}
    columns={columns}
    pageSize={20} //integer value representing max number of rows
    autoHeight={true}
/>
Run Code Online (Sandbox Code Playgroud)


vbo*_*tio 0

几天前我遇到了类似的问题,我解决了每次将新项目添加到我的行时重新计算行高的问题。

getRowHeight={(props: GridRowHeightParams) => {
      const serviceRowHeight = 45 // <-- default height, if I have no data for the row
      const addServiceBtnHeight = 45 // <-- a component that's always on the row
      const height = props.model?.services // services is each dynamic item for my row, so you should access like props.yourObj
        ? props.model.services.length * serviceRowHeight + addServiceBtnHeight
        : 115
      return height < 115 ? 115 : height // final height to be returned
    }}
Run Code Online (Sandbox Code Playgroud)