我正在使用React + Material 表。

实现什么

我想选择将pageSize设置为“全部”以匹配 Material 表中的总行数。

我做了什么

我使用useState创建rowsPerPage,并在handleChangeRowsPerPage函数中设置rowsPerPage。我使用组件重写来自定义分页,并将rowsPerPage和处理程序传递给它的 Prop 。我还将rowsPerPage传递给MaterialTable的pageSize选项。

问题我遇到

页面不会调整大小,并且state.pageSize不会更新。即使props.options.pageSize和Pagination使用onChangeRowsPerPage成功更新。

链接到sandbox

import React, { useState } from "react";
import MaterialTable from "material-table";
import { TablePagination } from "@material-ui/core";

export default function ComponentOverriding() {
  const [rowsPerPage, setRowsPerPage] = useState(5);
  //updates pagination, but no re-size
  const handleChangeRowsPerPage = event => {
    //enable to set rows per page to match total count
    event.target.value === "All"
      ? setRowsPerPage(data.length)
      : setRowsPerPage(event.target.value);
  };

  const data = [
    { name: "Mehmet", surname: "Baran", birthYear: 1987 },
    { name: "Zerya Betül", surname: "Baran", birthYear: 2017 }
  ];
  return (
    <MaterialTable
      title="Component Override Demo"
      columns={[
        { title: "Name", field: "name" },
        { title: "Surname", field: "surname" },
        { title: "Birth Year", field: "birthYear" }
      ]}
      data={data}
      //options.pageSize updates, but no re-size
      options={{ pageSize: rowsPerPage }}
      // onChangeRowsPerPage={handleChangeRowsPerPage} //TypeError Cannot read property 'value' of undefined
      components={{
        Pagination: props => (
          <TablePagination
            {...props}
            rowsPerPageOptions={[5, 10, 20, "All"]}
            rowsPerPage={rowsPerPage}
            //updates pagination, but no re-size
            onChangeRowsPerPage={handleChangeRowsPerPage}
          />
        )
      }}
    />
  );
}


最佳答案

我有解决办法,
无需自定义分页
只需更换

<MaterialTable
  options={{
    pageSize: rowsPerPage,
    pageSizeOptions: [5, 10, 20],
  }}
/>
<MaterialTable
  options={{
    pageSize: rowsPerPage,
    pageSizeOptions: [5, 10, 20, { value: data.length, label: 'All' }],
  }}
/>

10-06 12:20