首页 > 解决方案 > Material-ui tablepagination 各种报表每页默认行数

问题描述

我一直在关注关于 material-ui 的示例TablePagination,它们作为useTable组件具有并具有以下代码:

import React, { useState } from 'react'
import { Table, TableHead, TableRow, TableCell, makeStyles, TablePagination, TableSortLabel } from '@material-ui/core'

const useStyles = makeStyles(theme => ({
    table: {
        marginTop: theme.spacing(1),
        '& thead th': {
            fontWeight: '800',
            backgroundColor: '#e0e0e0',
            color: '#000'                      
        },
        '& tbody td': {
            fontWeight: '500',
        },
        '& tbody tr:hover': {
            backgroundColor: '#bee8fd',
            cursor: 'pointer',
        },
        minWidth: 650
    },
}))

export default function useTable(records, filterFn) {

    const classes = useStyles();

    const pages = [5, 10, 25, 50, 75, 100]
    const [page, setPage] = useState(0)
    const [rowsPerPage, setRowsPerPage] = useState(pages[page])
    const [order, setOrder] = useState()
    const [orderBy, setOrderBy] = useState()

    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    }

    const handleChangeRowsPerPage = event => {
        setRowsPerPage(parseInt(event.target.value, 10))
        setPage(0);
    }

    const TblPagination = () => (<TablePagination
        component="div"
        page={page}
        rowsPerPageOptions={pages}
        rowsPerPage={rowsPerPage}
        count={records.length}
        onChangePage={handleChangePage}
        onChangeRowsPerPage={handleChangeRowsPerPage}
    />)

    const recordsAfterPagingAndSorting = () => {
        return stableSort(filterFn.fn(records), getComparator(order, orderBy))
            .slice(page * rowsPerPage, (page + 1) * rowsPerPage)
    }

    return {
        TblPagination,
        recordsAfterPagingAndSorting
    }
}

在另一个名为 的组件中,我按如下方式JobReport.js导入此组件useTable

import useTable from "./useTable";

在我的报告的底部,我调用了<TblPagination />useTable.js

我的问题是,目前根据状态值将其设置为 5 useTable.jsrowsPerPage我希望能够实现的是为该组件提供useTable.js来自使用它的任何其他组件的动态值,以设置该组件的 rowPerPage。

因此,在ComponentA.js我可能有一个报告中,我想将其默认rowPerPage为 10,而在另一个组件中,我可能将该报告默认为 50,但两者仍然调用该useTable.js组件。

我以为我可以将其作为道具传递<TblPagination page={3}/>给返回 50,但这不起作用。

有了这个设置,无论如何我可以将我的行设置为默认为 50<TblPagination />

我实际上使用的 useTable.js 是许多不同的组件,并且希望能够跨这些不同的组件将 rowsPerPage 更改为不同的值。

如果我更改它,useTable.js那么所有调用它的组件将默认为 50 行,这不是我想要的。

标签: javascriptreactjspaginationmaterial-ui

解决方案


更新:赋予使用此钩子定义多少行每页的组件的能力。如果未定义,则将默认值设置为 50。

export default function useTable(records, filterFn, customRowsPerPage) {
  //..
  const [rowsPerPage, setRowsPerPage] = useState(customRowsPerPage || 50)
  //..
}

代替:

const [rowsPerPage, setRowsPerPage] = useState(pages[page])

将默认值设置为 50:

const [rowsPerPage, setRowsPerPage] = useState(50)

推荐阅读