React+AntD Table支持下拉分页和自定义输入分页条数

news/2024/11/20 10:49:18/文章来源:https://www.cnblogs.com/openmind-ink/p/18556366

实例

支持在下拉分页框内输入分页条数来实现自定义分页

代码

  • usePageSizeSelect.js
import {useEffect, useState} from "react";
import Bus from "../../utils/eventBus";export function usePageSizeSelect() {const onInputKeyDown = (e) => {const tempVal = e.target.value;if (String(e.key) === 'Enter') {console.log('output-> key', e.target.value)setVal(e.target.value)let totalOptions = [...pageOptions,{value: `${tempVal}`,label: `${tempVal}条/页`}]totalOptions.sort((a, b) => parseInt(a.value, 10) - parseInt(b.value, 10));setPageOptions(totalOptions)Bus.emit('handle-page-size-change', {pageSize: tempVal})}}const handleSelect = (val, option) => {setVal(val)Bus.emit('handle-page-size-change', {pageSize: val})}useEffect(() => {const resetPageOptionListener = () => {setVal('8')}Bus.addListener('reset-page-option', resetPageOptionListener)return () => {Bus.removeListener('reset-page-option', resetPageOptionListener)}}, []);const [val, setVal] = useState('8')const [pageOptions, setPageOptions] = useState([{value: '8',label: '8条/页',},{value: '32',label: '32条/页',},{value: '64',label: '64条/页',},{value: '128',label: '128条/页',},{value: '768',label: '768条/页',},{value: '1024',label: '1024条/页',},])return {onInputKeyDown,val,setVal,pageOptions,handleSelect}
}
  • PageSizeSelect.tsx
import { Select } from 'antd';
import React from 'react';
import {usePageSizeSelect} from "../../../hooks/keyMan/usePageSizeSelect";const PageSizeSelect = () => {const {val,setVal,onInputKeyDown,pageOptions,handleSelect} = usePageSizeSelect()return(<SelectclassName="page-size-selector"allowClearshowSearchdefaultValue="8"size={'small'}style={{ width: 160, marginBottom: 0, border: '2px solid #45526d', lineHeight: 0}}placeholder="请输入分页数"getPopupContainer={((triggerNode: any) => triggerNode.parentElement) as any}value={val}optionFilterProp="label"onInputKeyDown={e=> onInputKeyDown(e)}options={pageOptions}onSelect={handleSelect}/>)
}export default PageSizeSelect;
  • PageSizeSelect结合Table和Pagination组件使用
import React, {useEffect, useRef} from "react";
import keyManComStyl from "./KeyManComponent.styl";
import batchConcern from "../../assets/keyman/batchConcern.svg";
import batchSubscribe from "../../assets/keyman/batchSubscribe.svg";
import {ADD_CONTROL_COLS} from "../../utils/bean";
import {useKeyManTable} from "../../hooks/keyMan/layout/useKeyManTable";
import FilterBtnBox from "./FilterBtnBox";
import {message, Pagination, Popconfirm, Table} from "antd";
import BatchSubscribe from "../../pages/main/subscription/BatchSubscribe";
import SubscriberStore from "src/stores/modules/SubscriberStore";
import Bus from "../../utils/eventBus";
import PageSizeSelect from "./table/PageSizeSelect";
import EditKeyMan from "./modal/EditKeyMan";
import {useEditKeyMan} from "../../hooks/keyMan/useEditKeyMan";
import AllSubscribe from "../../pages/main/subscription/AllSubscribe";const KeyManTable = ({treeType, curSourceUnit}) => {const {rowSelection,pageNo,setPageNo,pageSize,setPageSize,searchData,pageTotal,onPaging,onPagingSizeChange,dataSource,loading,loadTableData,onBatchFocus,onBatchCancelFocus,selectedTableKeys,selectedTableRows,setSelectedTableKeys,setSelectedTableRows,} = useKeyManTable()const batchSubRef = useRef(null)const allSubscribeRef = useRef(null)const onShowBatchModalListener = (record:any) => {SubscriberStore.setSubscribers([record]) // cache selected rowif (batchSubRef?.current) {batchSubRef.current.showModal()}}const resetSelectedTableData = () => {SubscriberStore.setSubscribers([])setSelectedTableKeys([])setSelectedTableRows([])}const handlePageSizeSelect = ({pageSize}) => {setPageNo(1)setPageSize(pageSize)onPagingSizeChange(1, pageSize)}const {editKeyManRef,onShowEditKeyMan,} = useEditKeyMan()useEffect(() => {Bus.addListener('reset-selected-tableData', resetSelectedTableData)Bus.addListener('subscribe-modal-show', onShowBatchModalListener)Bus.addListener('handle-page-size-change', handlePageSizeSelect)Bus.addListener('edit-key-man-show', onShowEditKeyMan)return () => {Bus.removeListener('reset-selected-tableData', resetSelectedTableData)Bus.removeListener('subscribe-modal-show', onShowBatchModalListener)}}, []);return (<><section className={keyManComStyl["key-man-table"]}><div className="table-box custom-table-box"><Tablescroll={{y: '380px'}}rowSelection={{type: 'checkbox',...rowSelection}}size={"small"}rowKey={record => record.id}dataSource={dataSource}columns={ADD_CONTROL_COLS}pagination={false}loading={loading}/><div style={{display: 'flex', justifyContent: 'flex-end', alignItems: 'center'}}><span><Paginationcurrent={pageNo}pageSize={pageSize}total={pageTotal}showQuickJumperonChange={onPaging}showSizeChanger={false}// onShowSizeChange={onPagingSizeChange}showTotal={total => `共 ${total} 条`}/></span><span className="page-size-select-box" style={{ marginLeft: '14px'}}><PageSizeSelect/></span></div></div></section></>);
};export default KeyManTable
  • useKeymanTable.js 表格相关逻辑抽取
import {useEffect, useState} from "react";
import NewBaseDataService from 'src/services/baseData/newIndex'
import Bus from "../../../utils/eventBus";
import KeyManTableStore from "src/stores/modules/keyManTable";
import {message} from "antd";
import KeyManServices from "src/services/keyMan";
import {unique} from "../../../utils/bean";
export function useKeyManTable() {const [pageNo, setPageNo] = useState(1);const [pageSize, setPageSize] = useState(8);const [pageTotal, setPageTotal] = useState(0);const [dataSource, setDataSource] = useState([])const [loading, setLoading] = useState(false)const [searchData, setSearchData] = useState({pageNo,pageSize,dataSource: '',sourceUnit: '',businessLabel: '',belongingPlace: '',businessLabelRule: 'or',belongingPlaceRule: 'or'})const [cacheSearchData, setCacheSearchData] = useState({})const onPaging = (page) => {setPageNo(page)setPageSize(pageSize)setSearchData({...searchData,pageNo: page,})Bus.emit('on-paging-by-filter', {pageNo: page, pageSize})// loadTableData({pageNo: page, pageSize}, true).then(r => r)}const onPagingSizeChange = (page, pageSize) => {Bus.emit('on-paging-by-filter', {pageNo: page, pageSize})// loadTableData({pageNo: page, pageSize}, true).then(r => r)setPageNo(page)setPageSize(pageSize)}const [selectedTableKeys, setSelectedTableKeys] = useState([])const [selectedTableRows, setSelectedTableRows] = useState([])// 选中的行 去空,去重const selectedRowsUnique = (list = []) => {const rows = list.filter(Boolean)return unique([...selectedTableRows, ...rows])}// 点击取消/选中 单行  用户手动选择/取消选择某行的回调const onSelectRow = (record, selected, selectedRows) => {const newRows = selectedRowsUnique(selectedRows)const arr = newRows.filter(item => {if (item.id === record.id) {return selected}return true})setSelectedTableRows(arr)setSelectedTableKeys(arr.map(item => item.id))}// 点击取消/选中 一页的所有  用户手动选择/取消选择所有行的回调const onSelectAllRow = (selected, selectedRows, changeRows) => {let newRows = selectedRowsUnique(selectedRows)if (!selected) {const arr = changeRows.map(item => item.id)newRows = newRows.filter(item => !arr.includes(item.id))}setSelectedTableRows(newRows)setSelectedTableKeys(newRows.map(item => item.id))}// 选中项发生变化时的回调// const onChange = (selectedRowKeys, selectedRows, info) => {// }const rowSelection = {// onChange: onChange,onSelect: onSelectRow,onSelectAll: onSelectAllRow,getCheckboxProps: (record) => ({disabled: record.name === 'Disabled User', name: record.name,}), selectedRowKeys: selectedTableKeys};const loadTableData = async (param = {}, isCache = false) => {let payload = {...searchData,...param}if(isCache) {let cacheData = KeyManTableStore.getCacheSearchParam()payload = {...param,dataSource: cacheData.dataSource,sourceUnit: cacheData.sourceUnit,focus: cacheData.focus,}}KeyManTableStore.setCacheSearchParam(payload)setLoading(true)const res = await NewBaseDataService.getKeyPersons(payload);if (res.status === 200) {setLoading(false)setDataSource(res.data)setPageTotal(res.total)setLoading(false)}}const onPagingFromFilter = () => {const curPagingListener = (payload) => {let param = {...payload,}loadTableData(param, true).then(r => r)}Bus.addListener('filter-table-data-with-cur-paging', curPagingListener)return curPagingListener}const panelFilterListener = () => {const filterTableDataListener = (payload) => {let param = {...searchData, ...payload}loadTableData(param, true).then(r => r)}Bus.addListener('filter-table-data', )}// 其他:dataSource: 0( when dataSource === 0 => sourceUnit)const treeFilterListener = () => {const treeFilterTableDataListener = (payload) => {setPageNo(1)setSearchData({...searchData,pageNo: 1,pageSize: 8,businessLabel: '',belongingPlace: '',businessLabelRule: 'or',belongingPlaceRule: 'or',})let param = {...searchData, ...payload,}if (param.sourceUnit === 'all') {param.sourceUnit = ''param.dataSource = ''param.businessLabelRule = 'or'param.belongingPlaceRule = 'or'}loadTableData(param).then(r => r)}Bus.addListener('tree-filter-table-data', treeFilterTableDataListener)return treeFilterTableDataListener}useEffect(() => {loadTableData().then(r => r)const filterTableDataListener = (payload) => {let param = {...searchData, ...payload}loadTableData(param, true).then(r => r)}Bus.addListener('filter-table-data', filterTableDataListener)const treeFilterTableDataListener = treeFilterListener()const fromFilterListener = onPagingFromFilter()const commonTableDataListener = () => {loadTableData({}, true).then(r => r)setSelectedTableRows([])setSelectedTableKeys([])}Bus.addListener('common-table-data', commonTableDataListener)Bus.addListener('reset-paging', resetSearchParam)return () => {console.log('output-> 【UnMount】', )Bus.removeListener('reset-paging', resetSearchParam)Bus.removeListener('common-table-data', commonTableDataListener)Bus.removeListener('tree-filter-table-data', treeFilterTableDataListener)Bus.removeListener('filter-table-data', filterTableDataListener)Bus.removeListener('filter-table-data-with-cur-paging', fromFilterListener)}}, [])// 筛选const handleFilter = () => {setLoading(true)// loadTableData()}// 简单筛选const handleSimpleFilter = () => {}// 重置const resetSearchParam = () => {setPageNo(1)setPageSize(8)Bus.emit('reset-page-option')}// 批量关注const onBatchFocus = async () => {if(!selectedTableKeys.length) {message.warn('请选择待关注人')return}const res = await KeyManServices.batchKeyManFocus(selectedTableKeys)if(res.status === 200) {setSelectedTableKeys([])await loadTableData({}, true)Bus.emit('refresh-left-tree')message.success('操作成功')}}// 批量取消关注const onBatchCancelFocus = async () => {if(!selectedTableKeys.length) {message.warn('请选择待取消关注人')return}const res = await KeyManServices.batchCancelConcern(selectedTableKeys)if(res.status === 200) {setSelectedTableKeys([])await loadTableData({focus: 1})Bus.emit('refresh-left-tree')message.success('操作成功')}}return {pageNo,setPageNo,pageSize,setPageSize,pageTotal,searchData,setSearchData,onPaging,rowSelection,dataSource,handleFilter,loading,selectedTableKeys,selectedTableRows,loadTableData,onPagingSizeChange,onBatchFocus,onBatchCancelFocus,setSelectedTableKeys,setSelectedTableRows,}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/837236.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode 2455[可被三整除的偶数平均值]

LeetCode 2455[可被三整除的偶数平均值]题目 链接 LeetCode 2455[可被三整除的偶数平均值] 详情实例提示题解 思路 遍历容器,for 循环遍历,vector 的 at 方法取元素值 判断能否被3整除,不能则继续遍历 能被3整除则判断能否被2整除,即判断奇偶性,不能被2整除,即为奇数则继…

Microsoft.Extensions.AI 初探

本文介绍了Microsoft.Extensions.AI的基本使用。.NET Conf上的介绍 在今年的.NET Conf上Steve Sanderson带来了题为“AI Building Blocks - A new, unified AI layer”的演讲。该演讲的主要内容如下: “大多数.NET应用程序可以通过AI功能变得更加强大和高效,例如语义搜索、自…

如何确定合适的绩效考核周期和频率?

绩效考核周期的确定需要根据企业的实际情况、不同岗位的特殊性、考核指标的性质及考核标准的不同进行综合考虑。 1、一般来说,管理层级越高的岗位,其考核周期也应该设置得相对较长 2、绩效考核周期过短会增加企业的管理成本;过长又会降低绩效考核数据的准确性比如,销售人员…

什么是OA办公系统?为什么OA办公系统对于企业的作用越来越重要?

如何提升工作效率、优化资源配置、加强团队协作能力,成为了每个企业管理者亟需解决的关键问题。随着企业规模的扩展和业务流程的复杂化,传统的手工操作和纸质文件已经无法满足高效办公的需求。 OA(Office Automation)办公系统应运而生,成为了现代企业提高工作效率、优化管…

关于湖北移动机顶盒CM311-1S长虹版本刷机的总结

最近家里的机顶盒不好使了,就捣鼓了一下自己刷机, 机顶盒是湖北移动的CM311-1s,长虹代工的,晶晨的S905L3处理器,2+8G的配置,用着也还行 这个版本的刷机需要拆机顶盒,找内部的短接点,就是背面这个“4R12”的电阻, 刷机需要用到USB双A头线,接靠近后排插座的那个口,插…

从零搭建UVM验证平台 简介

搭建UVM流程:定义interface。Interface是连接DUT和验证平台的桥梁,根据DUT的输入输出参数定义interface,在top_tb里连接interface和DUT。加入transaction。transaction是一个数据包,transaction由sequence产生,通过sequencer传递给driver。加入driver。Driver负责将接收到…

智慧城市时空基础设施建设与应用实践

智慧城市作为现代城市发展的新趋势,其核心在于利用先进的信息技术,实现城市运行的高效、智能和绿色。时空基础设施作为智慧城市建设的基石,为城市的智慧化提供了基础支撑。本文将探讨智慧城市时空基础设施的建设与应用实践。1. 时空基础设施的重要性时空基础设施是智慧城市不…

echarts 使用移表盘实现类似类目轴效果,不使用数值刻度

思路:使用多个移表盘叠加 效果图:代码: setGaugeChart() {this.gaugeChart && this.gaugeChart?.dispose && this.gaugeChart?.dispose()this.gaugeChart = echarts.init(this.$refs.gaugeChartRef)const grades = [AAA, AA, A, BBB, BB, B, CCC, CC, C, …

Chrome 浏览器 131 版本新特性

Chrome 浏览器 131 版本新特性 一、Chrome 浏览器 131 版本新特性 1. 在 iOS 上使用 Google Lens 搜索 自 Chrome 126 版本以来,用户可以通过 Google Lens 搜索屏幕上看到的任何图片或文字。 要使用此功能,请访问网站,并点击聚焦时出现在地址栏的 Google Lens 搜索按钮,或者…

Qt 重写paintEvent事件划线

可以自定义一个类QtImageLabel继承于QLabel,重写paintEvent事件划线,写文字等。如果用 ui 设计,将 QLabel 控件提升为 QtImageLabel 类型即可。QtImageLabel.h protected:void paintEvent(QPaintEvent *) override;QtImageLabel.cpp #pragma execution_character_set("…

递归定义

GNU “GNU”是“GNUs Not Unix!”(GNU并非Unix!)的首字母递归缩写。 平衡二叉树 也叫AVL树,它或者是一颗空树,或者具有以下性质的二叉排序树:它的左子树和左子树的高度之差(平衡因子)的绝对值不超过1,且它的左子树和右子树都是一颗平衡二叉树。 前序遍历 (preorder tra…

【GreatSQL优化器-03】查询开销估算

【GreatSQL优化器-03】查询开销估算 一、cost和read_time介绍 GreatSQL的优化器在创建执行计划的时候是根据每张表的行数和数据分布以及读数据硬盘消耗等信息来判断先查询哪张表后查询哪张表,要不要使用索引,这些表资源信息就被称为cost,俗称为"开销"。在这之前已…