Antd ProComponents中的EditableProTable無法在子行繼續新增子行的解決方案

一、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;
  };

成功解決瞭該問題,解決後的效果:

到此這篇關於Antd ProComponents中的EditableProTable無法在子行繼續新增子行的解決方案的文章就介紹到這瞭,更多相關Antd ProComponents子行內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: