Antd-ProComponents中的EditableProTable无法在子行继续新增子子行的临时解决方案

x33g5p2x  于2022-08-17 转载在 其他  
字(2.9k)|赞(0)|评价(0)|浏览(264)

一、BUG效果如下

点击后报错:

二、复现代码

import { EditableProTable } from '@ant-design/pro-table';
import React, { useState } from 'react';

const defaultData: any = new Array(3).fill(1).map((_, index) => {
  return {
    id: (Date.now() + index).toString(),
    title: `活动名称${index}`,
    decs: '这个活动真好玩',
    state: 'open',
    created_at: '2020-05-26T09:42:56Z',
  };
});

export default () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() =>
    defaultData.map((item) => item.id),
  );
  const [dataSource, setDataSource] = useState<any[]>(() => defaultData);

  const columns: any = [
    {
      title: '活动名称',
      dataIndex: 'title',
      width: '30%',
      formItemProps: {
        rules: [
          {
            required: true,
            whitespace: true,
            message: '此项是必填项',
          },
          {
            message: '必须包含数字',
            pattern: /[0-9]/,
          },
          {
            max: 16,
            whitespace: true,
            message: '最长为 16 位',
          },
          {
            min: 6,
            whitespace: true,
            message: '最小为 6 位',
          },
        ],
      },
    },
    {
      title: '状态',
      key: 'state',
      dataIndex: 'state',
      valueType: 'select',
      valueEnum: {
        all: { text: '全部', status: 'Default' },
        open: {
          text: '未解决',
          status: 'Error',
        },
        closed: {
          text: '已解决',
          status: 'Success',
        },
      },
    },
    {
      title: '描述',
      dataIndex: 'decs',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: () => {
        return null;
      },
    },
  ];

  return (
    <>
      <EditableProTable<any>
        headerTitle="可编辑表格"
        columns={columns}
        rowKey="id"
        scroll={{
          x: 960,
        }}
        value={dataSource}
        onChange={setDataSource}
        recordCreatorProps={{
          newRecordType: 'dataSource',
          position: 'bottom',
          record: () => ({
            id: Date.now(),
          }),
        }}
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [defaultDoms.delete,
            <EditableProTable.RecordCreator
              parentKey={row.id}
              newRecordType='dataSource'
              position='bottom'
              record={{
                id: Date.now(),
              }}
            >
              <a>增加子行</a>
            </EditableProTable.RecordCreator>];
          },
          onValuesChange: (record, recordList) => {
            setDataSource(recordList);
          },
          onChange: setEditableRowKeys,
        }}
      />
    </>
  );
};

三、解决方案

自己写一个递归的方法将子行追加到选中行下即可,下面展示的是我项目中的代码,不能复制直接用,但思路是一样的。
首先在actionRender中自定义“增加子行”的操作按钮,其中addChildToSource为增加逻辑方法:

actionRender: (row, _, dom) => [
            <a
              key="addChild"
              onClick={() => addChildToSource(row.id, type)}
            >
              增加子行
            </a>
          ],

addChildToSource代码如下:

//增加子行
  const addChildToSource = (rowKey: any, type: string) => {
    let childRowKey = Date.now(); //rowkey的id不能重复,不然会回填异常
    editableKeys[type].push(childRowKey);
    let source = formRef.current.getFieldValue(`${type}_source`); //type_source为表格定义的formItem的name
    source = addChildToSourceFunc(source, rowKey, childRowKey, type);
    const _dict = {};
    _dict[`${type}_source`] = source;
    formRef.current.setFieldsValue(_dict);
    setEditableKeys({ ...editableKeys });
  };

上述方法调用的addChildToSourceFunc代码如下:

//删除参数edit及子级edit
   const addChildToSourceFunc = (
    source: any,
    rowKey: any,
    childRowKey: any,
    type: string,
    childName: any = null,
  ) => {
    for (var i = 0; i < source.length; i++) {
      const sourceItem = source[i];
      if (sourceItem.id === rowKey) {
        if (!sourceItem.children) {
          sourceItem.children = [];
        }
        sourceItem.children.push({ id: childRowKey, required: true, param_type: 'string', name: childName });
        break;
      } else if (sourceItem.children) {
        addChildToSourceFunc(sourceItem.children, rowKey, childRowKey, type, childName,);
      }
    }
    return source;
  };

成功解决了该问题,解决后的效果:

相关文章

微信公众号

最新文章

更多