问题:
antd Table提供了数据行可选择的操作,但是如果分页数据是从后端获取,切换页码后之前的分页数据就没有了,回到之前的页面选中状态也无法保留。
解决:
这里对ant Table表格组件进行了封装,实现了在分页数据动态获取时切换页码其他页选中的数据和状态仍保留的功能
思路:
1.定义curPageSelectedRowKeys存储当前页选中数据的key值数组,selectedRows存储所有选中数据
2.监听当前页数据选中/取消选中和全选/取消全选操作,更新curPageSelectedRowKeys和selectedRows
3.当页码切换时根据selectedRows来确定当前页面哪些数据是选中状态从而确定curPageSelectedRowKeys
组件代码:
/*
* @Author: liu
* @Date: 2021-08-24 14:35:53
* @LastEditTime: 2021-09-08 22:11:01
* @LastEditors: Please set LastEditors
* @Description: 表格自定义选中项,前端分页,分页后保留之前选中数据
* @FilePath: \chq-datamarket-frontend\src\apps\views\shared\customSelectTable\customSelectTable.tsx
*/
import React, {
useEffect, useState } from "react";
import {
Pagination, Table } from "antd";
interface CustomSelectTableProps {
columns: any[]; //表格列
dataSource: any[]; //表格数据(当前页)
curPageSelectedRowKeys: number[]; //当前页选中数据key值数组
curPageSelectedRowKeysChange: (key: any[]) => void; //curPageSelectedRowKeys改变
selectedRows: any[]; //所有选中数据
selectedRowsChange: (row: any[]) => void;
pageOption: {
//分页参数
page: number;
pageChange: (page) => void;
pageSize: number;
sizeChange: (size: number) => void;
totalCount: number;
showSizeChanger?: boolean;
pageSizeOptions?: any[];
};
tableClass?: string;
}
export default function customSelectTable(props: CustomSelectTableProps) {
useEffect(() => {
updateSelectData();
}, [props.dataSource]);
const rowSelection = {
selectedRowKeys: props.curPageSelectedRowKeys,
onSelect: (record, selected, selectedRows, nativeEvent) => {
onSelectChange(record, selected, selectedRows);
},
onSelectAll: onSelectAll,
hideDefaultSelections: true
};
/**
* 更新选中数据,当表格数据变化后,重新计算当前页选中数据
*/
function updateSelectData() {
const curPageSelectIndex = [];
const {
selectedRows } = props;
if (selectedRows && selectedRows.length) {
props.dataSource.map(d => {
selecte

本文档介绍了一种在Ant Design Table组件中实现分页数据选中状态跨页保留的方法。通过定义当前页选中数据key值数组和所有选中数据数组,监听选中操作并更新状态。在页码切换时,根据已选中的数据确定新页面的选中状态。代码示例展示了如何封装Table组件以及使用场景。
最低0.47元/天 解锁文章
644

被折叠的 条评论
为什么被折叠?



