【发布时间】:2021-08-14 10:01:50
【问题描述】:
我一直在关注关于 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";
在报告的底部,我调用了从useTable.js 返回的组件<TblPagination />
我的问题是,目前在useTable.js 内,rowsPerPage 根据状态值设置为 5。我希望能够实现的是为这个 useTable.js 组件提供一个来自任何其他使用它的组件的动态值,以设置该组件的 rowPerPage。
所以在ComponentA.js 中,我可能有一个报告,我想将rowPerPage 默认为10,而在另一个组件中,我可能将该报告默认为50,但两者仍然调用useTable.js 组件。
我以为我可以将其作为道具传递给 <TblPagination page={3}/> 以返回 50,但这不起作用。
有了这个设置,我可以在<TblPagination />中将我的行默认设置为50
我实际上使用 useTable.js 是许多不同的组件,并希望能够跨这些不同的组件将 rowsPerPage 更改为不同的值。
如果我在 useTable.js 中更改它,那么所有调用它的组件将默认为 50 行,这不是我想要的。
【问题讨论】:
-
你是如何在其他组件中渲染 TblPagination 的?
-
@Shyam - 如我的问题中所述 - 我只是在报告底部调用组件
<TblPagination />。 -
你能不能试着这样称呼它
{TblPagination(50)},在你的useTable钩子中你可以用const TblPagination = (rowsPerPage)访问它
标签: javascript reactjs pagination material-ui