Ant-Design-Pro-Components:ProTable组件后台请求数据,表格实现跨页多选,修改行信息,批量提交修改。

一、业务需求:

讲师星级实现跨页批量调整星级
Ant-Design-Pro-Components:ProTable组件后台请求数据,表格实现跨页多选,修改行信息,批量提交修改。_第1张图片

1. 相关API:

  • editable: 可编辑表格的相关配置
    editable 编辑行配置
    type: 单行 single | 多行 multiple在这里插入图片描述
    部分代码:
editable={{
  type: 'multiple',
  actionRender: (row, config, defaultDom) => [defaultDom?.save, defaultDom.cancel],
  onSave: (key, row) => {
    // console.log('当前行保存按钮', key, row, 'mySelectedRow', mySelectedRow);
    // 处理先勾选然后编辑修改调整
    mySelectedRow.forEach((item) => {
      if (item.staffCode == row.staffCode) {
        item.teachLevel = row.teachLevel;
      }
    });
  },
}}
  • rowSelection: 表格行是否可选择 ,属性来源参考 :Table表格
    在这里插入图片描述
    selectedRowKeys: 指定选中项的 key 数组,需要和 onChange 进行配合
    Ant-Design-Pro-Components:ProTable组件后台请求数据,表格实现跨页多选,修改行信息,批量提交修改。_第2张图片
    onChange: 选中项发生变化时的回调
    onSelect: 用户手动选择/取消选择某行的回调
    onSelectAll: 用户手动选择/取消选择所有行的回调
    onSelectMultiple: 用户使用键盘 shift 选择多行的回调

部分代码:

   rowSelection={{
      selectedRowKeys: mySelectedRowKeys,
      onSelect, //用户手动选择/取消选择某行的回调
      onSelectMultiple: onMulSelect, //用户使用键盘 shift 选择多行的回调
      onSelectAll: onMulSelect, //用户手动选择/取消选择所有行的回调
      onChange, //选中项发生变化时的回调
 }}
  • tableAlertRender 自定义批量操作工具栏左侧信息区域, false 时不显示
  • tableAlertOptionRender 自定义批量操作工具栏右侧选项区域, false 时不显示
    Ant-Design-Pro-Components:ProTable组件后台请求数据,表格实现跨页多选,修改行信息,批量提交修改。_第3张图片
    部分代码:
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
          // if (tableAlertRenderShow) {
          return (
            <Space size={24}>
              <Button
                type="primary"
                key="primarynew"
                loading={bulkOperationLoading}
                onClick={() => {
                  bulkOperation(mySelectedRowKeys, mySelectedRow);
                  // bulkOperation(mySelectedRowKeys);
                }}
              >
                批量调整({mySelectedRowKeys.length})
              </Button>
              <span>
                <a
                  style={{ marginInlineStart: 8 }}
                  onClick={() => {
                    handleMySelectedRowKeys([]);
                    handleMySelectedRow([]);
                    setBulkOperationLoading(false);
                  }}
                >
                  取消选择
                </a>
              </span>
            </Space>
          );
          // }
        }}
        tableAlertOptionRender={() => {
          return false;
        }}

二、完整代码:

import React, { useRef, useState, Fragment, useEffect } from 'react';
import { getWqStartLecturerList, updateLevel } from '@/services/train/personnel';
import { getOrgList, getSelectType } from '@/services/globalServices';
import { PlusOutlined, EditTwoTone, DeleteTwoTone } from '@ant-design/icons';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Form, Space } from 'antd';
import { FormattedMessage } from 'umi';
import EditForm from './components/editForm';

const LecturerStarAdjustment = () => {
  const actionRef = useRef(); // 表格组件ProTable ref
  const [modalVisible, handleModalVisible] = useState(false); // 新建窗口  编辑 的弹窗
  const [currentRow, setCurrentRow] = useState(); // 当前行数据
  const [mySelectedRowKeys, handleMySelectedRowKeys] = useState([]); // 选中的行的id key值
  let cancleRowKeys = []; // 取消选择的行的id  key值  // 由于cancleRowKeys不影响dom,所以不使用useState定义
  const [mySelectedRow, handleMySelectedRow] = useState([]); // 选中的行的信息
  let cancleRow = []; // 取消选择的行的信息
  const [editableBtn, setEditableBtn] = useState(true); // 操作列编辑按钮
  const [bulkOperationLoading, setBulkOperationLoading] = useState(false); // 操作操作loading
  const [orgList, setOrgList] = useState([]); // 管理机构
  const [orgObj, setOrgObj] = useState({}); // 管理机构对象
  const [orgObj2, setOrgObj2] = useState({}); // 管理机构对象
  const [starLevelArray, setStarLevelArray] = useState([]); // 星级
  const [tableAlertRenderShow, setTableAlertRenderShow] = useState(true); // 表格顶部信息栏显示
  useEffect(() => {
    getSelectTypeFun();
  }, []);
  const getSelectTypeFun = async () => {
    await getOrgList().then((res) => {
      if (res && res.data) {
        setOrgList(res.data);
        var newObj = {};
        var newObj2 = {};
        res.data.forEach((item) => {
          newObj2[item.comcode] = item.name;
          newObj[item.name] = item.comcode; // 逆向处理把中文转成机构编码
        });
        setOrgObj(newObj);
        setOrgObj2(newObj2);
      } else {
        setOrgList([]);
        setOrgObj({});
        setOrgObj2({});
      }
    });
    await getSelectType('teacherlevel').then((res) => {
      if (res && res.data) {
        setStarLevelArray(res.data);
      }
    });
    // await getSelectType('stationcode').then((res) => {
    //   // if (res && res.data) {
    //   //   setStarLevelArray(res.data);
    //   // }
    // });
  };

  const onSelect = (record, selected) => {
    setTableAlertRenderShow(true);
    if (!selected) {
      cancleRowKeys = [record.staffCode];
      cancleRow = [record];
    }
  };

  const onMulSelect = (selected, selectedRows, changeRows) => {
    setTableAlertRenderShow(true);
    if (!selected) {
      cancleRowKeys = changeRows.map((item) => item.staffCode);
      cancleRow = changeRows.map((item) => item);
    }
  };

  const onChange = (selectedRowKeys, selectedRows) => {
    setTableAlertRenderShow(true);
    if (cancleRowKeys.length) {
      const keys = mySelectedRowKeys.filter((item) => !cancleRowKeys.includes(item));
      handleMySelectedRowKeys(keys);
      cancleRowKeys = [];
    } else {
      handleMySelectedRowKeys([...new Set(mySelectedRowKeys.concat(selectedRowKeys))]);
    }

    if (cancleRow.length) {
      const rows = mySelectedRow.filter(
        (item) => !cancleRow.some((ele) => ele.staffCode === item.staffCode),
      );
      console.log('rows', rows, 'mySelectedRow', mySelectedRow, 'cancleRow', cancleRow);
      handleMySelectedRow(rows);
      cancleRow = [];
    } else {
      handleMySelectedRow([...new Set(mySelectedRow.concat(selectedRows))]);
    }
  };

  const reset = () => {
    setBulkOperationLoading(false);
    setTableAlertRenderShow(false);
    handleMySelectedRow([]);
    handleMySelectedRowKeys([]);
  };

  // 批量操作按钮
  const bulkOperation = (selectedRowKeys, mySelectedRow) => {
    // console.log('批量操作按钮selectedRowKeys===', selectedRowKeys);
    // console.log('批量操作按钮mySelectedRow===', mySelectedRow);
    // 处理mySelectedRow staffCode有重复的数据
    let hash = [];
    const newArr = mySelectedRow.reduce((pre, cur) => {
      hash[cur.staffCode] ? '' : (hash[cur.staffCode] = true && pre.push(cur));
      return pre;
    }, []);
    // console.log('过滤掉重复的数据newArr===', newArr);

    // 判断数组里面调整星级字段有没有空值
    let flag = newArr.every((item) => {
      // console.log('every+item', item, !item.teachLevel);
      if (!item.teachLevel) {
        message.error(`工号:${item.staffCode},调整后星级不能为空!`);
        return;
      }
      return item.teachLevel != null || item.teachLevel != '';
    });
    // console.log('flag', flag);
    if (flag == true) {
      // 处理成 提交后台所需要的数据格式
      const newArray = [];
      newArr.forEach((item) => {
        newArray.push({
          trainCode: item.trainCode,
          staffCode: item.staffCode,
          teachLevel: item.teachLevel,
        });
      });
      // console.log('newArray===', newArray);
      if (newArray.length > 0) {
        // 接口更新星级
        setBulkOperationLoading(true);
        updateLevel(newArray).then((res) => {
          if (res && res.success) {
            reset();
            if (actionRef.current) {
              actionRef.current.reload();
            }
          } else {
            message.error(res.message);
            reset();
          }
        });
      }
    }
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'staffCode',
      editable: false,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      editable: false,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      editable: false,
      search: false,
    },
    {
      title: '管理机构',
      dataIndex: 'manageCom',
      valueType: 'select',
      fieldProps: {
        options: orgList,
        fieldNames: {
          label: 'name',
          value: 'comcode',
        },
      },
      editable: false,
    },
    {
      title: '入司时间',
      dataIndex: 'joinWorkDate',
      valueType: 'date',
      editable: false,
      search: false,
    },
    {
      title: '职级',
      dataIndex: 'agentCode',
      search: false,
      editable: false,
    },
    {
      title: '当前导师星级',
      dataIndex: 'teachLevelCode',
      editable: false,
      valueType: 'select',
      fieldProps: {
        options: starLevelArray,
        fieldNames: {
          label: 'codename',
          value: 'code',
        },
      },
    },
    {
      title: '评聘日期',
      dataIndex: 'engageDate',
      valueType: 'date',
      search: false,
      editable: false,
    },
    {
      title: '课时统计',
      dataIndex: 'time',
      search: false,
      editable: false,
      width: 120,
    },
    {
      title: '调整后星级',
      dataIndex: 'teachLevel',
      search: false,
      width: 120,
      valueType: 'select',
      fieldProps: {
        options: starLevelArray,
        fieldNames: {
          label: 'codename',
          value: 'code',
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" />,
      dataIndex: 'option',
      valueType: 'option',
      width: 100,
      render: (_, row, index, action) => [
        <>
          {editableBtn ? (
            <a
              key={row?.staffCode}
              onClick={() => {
                action?.startEditable(row?.staffCode);
              }}
            >
              <EditTwoTone />
              编辑
            </a>
          ) : null}
        </>,
      ],
    },
  ];

  return (
    <PageContainer breadcrumb={false}>
      <ProTable
        loading={bulkOperationLoading}
        headerTitle="查询列表"
        rowKey={'staffCode'}
        actionRef={actionRef}
        search={{
          labelWidth: 120,
          defaultCollapsed: false,
        }}
        pagination={{
          pageSize: 10,
          onChange: (page) => {
            setTableAlertRenderShow(false);
          },
        }}
        options={false}
        revalidateOnFocus={false}
        request={(params) => getWqStartLecturerList({ ...params })}
        columns={columns}
        editable={{
          type: 'multiple',
          actionRender: (row, config, defaultDom) => [defaultDom?.save, defaultDom.cancel],
          onSave: (key, row) => {
            // console.log('当前行保存按钮', key, row, 'mySelectedRow', mySelectedRow);
            // 处理先勾选然后编辑修改调整
            mySelectedRow.forEach((item) => {
              if (item.staffCode == row.staffCode) {
                item.teachLevel = row.teachLevel;
              }
            });
          },
        }}
        rowSelection={{
          selectedRowKeys: mySelectedRowKeys,
          onSelect, //用户手动选择/取消选择某行的回调
          onSelectMultiple: onMulSelect, //用户使用键盘 shift 选择多行的回调
          onSelectAll: onMulSelect, //用户手动选择/取消选择所有行的回调
          onChange, //选中项发生变化时的回调
        }}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
          // if (tableAlertRenderShow) {
          return (
            <Space size={24}>
              <Button
                type="primary"
                key="primarynew"
                loading={bulkOperationLoading}
                onClick={() => {
                  bulkOperation(mySelectedRowKeys, mySelectedRow);
                  // bulkOperation(mySelectedRowKeys);
                }}
              >
                批量调整({mySelectedRowKeys.length})
              </Button>
              <span>
                <a
                  style={{ marginInlineStart: 8 }}
                  onClick={() => {
                    handleMySelectedRowKeys([]);
                    handleMySelectedRow([]);
                    setBulkOperationLoading(false);
                  }}
                >
                  取消选择
                </a>
              </span>
            </Space>
          );
          // }
        }}
        tableAlertOptionRender={() => {
          return false;
        }}
      />
      {modalVisible ? (
        <EditForm
          currentRow={currentRow}
          modalVisible={modalVisible}
          handleModalVisible={handleModalVisible}
          setCurrentRow={setCurrentRow}
          actionRef={actionRef}
        />
      ) : (
        ''
      )}
    </PageContainer>
  );
};

export default LecturerStarAdjustment;

Ant-Design-Pro-Components: ProTable表格实现跨页多选。

你可能感兴趣的:(Ant,Design,react.js,前端)