antd Table(表格)组件跨页选数据

227 阅读1分钟

项目背景:

表格数据通过分页请求服务端数据来渲染,即前端拿到的不是全部数据,只是部分数据

需求:

a)用户需要一次选取好几页数据(包含全选当前页和勾选几条切页再选)。b)根据搜索条件选择数据,比如第一种搜索条件下选中几条数据,然后清空搜索条件,在第二种搜索条件下再选中几条数据。

    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
    const [selectedKeysInfo, setSelectedKeysInfo] = useState<any[]>([]);
    const rowSelection = {
      selectedRowKeys: selectedKeys,
      onSelect: (record: any, selected: boolean) => {
        if (selected) {
          // 选中某条数据
          setSelectedKeys(selectedKeys.concat([record[rowKey]]));
          setSelectedKeysInfo(selectedKeysInfo.concat([record]));
        } else {
          // 取消选中某条
          setSelectedKeys(selectedKeys.filter((v) => v !== record[rowKey]));
          setSelectedKeysInfo(
            selectedKeysInfo.filter((v) => v[rowKey] !== record[rowKey]),
          );
        }
      },
      onSelectAll: (selected: boolean, selectedRows: any, changeRows: any) => {
        if (selected) {
          // 当前页全部选中
          // 使用set是防止数据重复,可能存在先单条勾选,然后再全选当前页
          const set1 = new Set(selectedKeys);
          const set2 = new Set(selectedKeysInfo);
          changeRows.forEach((v: any) => {
            set1.add(v[rowKey]);
            set2.add(v);
          });
          setSelectedKeys([...set1]);
          setSelectedKeysInfo([...set2]);
        } else {
          // 当前页取消全部选中
          const arr1 = selectedKeysInfo.filter((v) => {
            return !changeRows.some((i: any) => i[rowKey] === v[rowKey]);
          });
          const arr2 = selectedKeys.filter((v) => {
            return !changeRows.some((i: any) => i[rowKey] === v);
          });
          setSelectedKeys([...arr2]);
          setSelectedKeysInfo([...arr1]);
        }
      },
    };
<Table rowSelection={{ type: 'checkbox', ...rowSelection}} />