关于antdpro的EdittableProTable编辑时两个下拉搜索框的数据联动以及数据回显(以及踩坑)

news2024/9/21 2:30:37

需求:使用antdpro的editprotable编辑两个下拉框,且下拉框是一个搜索下拉框。下拉框1和2的值是一个编码和名字的联动关系,1变化会带动2,2变化会带动1的一个联动作用。(最后有略完整的代码,但是因为公司项目问题,删掉了一些不必要的代码,不确保运行成功)

在这里插入图片描述

我使用的是renderFormItem进行渲染Select,并绑定了form

修改对应的下拉框数据不难,但是数据回显比较难,我网上看了好多,很多是说绑定form,用form.setfieldValue,但是我一直失败显示不出来,网上也没搜到我这个回显的方法,官方文档也写得很少。

最后是试出来的方式。

1、使用antdpro的EdittableProTable

<EditableProTable<AdminAccountItem>
            columns={columns}
            actionRef={actionRef}
            cardBordered
            form={tableForm}
            request={async (params = {}, sort, filter) => {
                console.log(sort, filter);
                // await waitTime(2000);
                setExParam(params as unknown as AdminAccountItem);
                return request<{
                    data: AdminAccountItem[];
                }>('/getList', {
                    params,
                }).then(res => {
                    setListData(res.data)
                    return res
                });
            }}
            editable={{
                form: tableForm,
                editableKeys,
                // type: 'multiple',
                onSave: async (rowKey, data, row) => {
                    // console.log('============', tableForm.getFieldsValue[editableKeys[0]]());
                    console.log('row', data);
                    await adminApi.updateAdmin(data)
                  },
                onCancel:async () => {
                    
                },
                onChange: setEditableRowKeys,
                // 设置编辑只留保存和取消按钮
                actionRender: (row, config, dom) => [dom.save, dom.cancel],
              }}
            value={listData}
            onChange={setListData}
            columnsState={{
                persistenceKey: 'pro-table-singe-demos',
                persistenceType: 'localStorage',
                onChange(value) {
                    console.log('value: ', value);
                },
            }}
            rowKey="id"
            search={{
                labelWidth: 'auto',
            }}
            options={{
                setting: {
                    listsHeight: 400,
                },
            }}

            form={{
                // 由于配置了 transform,提交的参与与定义的不同这里需要转化一下
                syncToUrl: (values, type) => {
                    if (type === 'get') {
                        return {
                            ...values,
                            created_at: [values.startTime, values.endTime],
                        };
                    }
                    return values;
                },
            }}
            pagination={{
                pageSize: 10,
                onChange: (page) => console.log(page),
            }}
            // toolbar={{
            //     actions: []
            // }}
            dateFormatter="string"
            headerTitle="管理员列表"
        >
        </EditableProTable>

这里面比较重要的参数一个就是
这两个决定了在表格中点击编辑修改然后保存之后,数据会不会回显到表格中(我前面看了很多教程把onchange注释掉了所以修改后一直回显不出来,走了蛮多弯路)

value={listData}
onChange={setListData}

还有一个就是edittable了,里面最重要的就是
form:tableForm

const [tableForm] = Form.useForm<AdminAccountItem>();

form在数据联动起很重要的作用,但是也因为它的用法,普通表单容易修改,但是用在列表中,找不到用法,走了很多弯路。

还有一个就是编辑行的key值,也是你table设置的key值,editableKeys,其他可以看看官网

const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])

这个在后面数据联动和tableForm一起使用起到重要作用。

editable={{
                form: tableForm,
                editableKeys,
                // type: 'multiple',
                onSave: async (rowKey, data, row) => {
                    // console.log('============', tableForm.getFieldsValue[editableKeys[0]]());
                    console.log('row', data);
                    await adminApi.updateAdmin(data)
                  },
                onCancel:async () => {
                    
                },
                onChange: setEditableRowKeys,
                // 设置编辑只留保存和取消按钮
                actionRender: (row, config, dom) => [dom.save, dom.cancel],
              }}

2、表格column的设置

我这里需要修改的是组织id和组织名称
设置两个onSelect选中时获取远程数据

{
            title: '组织ID',
            dataIndex: 'orgId',
            copyable: true,
            ellipsis: true,
            hideInSearch: true,
            valueType: 'select',
            renderFormItem: (_, data, form) => {
                return (
                        <Select
                            options={orgOptions}
                            showSearch={true}
                            onSelect={onOrgIdSelect}
                            onSearch={(value) => getList('orgId', value)}
                            >
                        </Select>
                )
            },
            render: (_, data) => {
                return <div>{data.orgId}</div>
            }
        },
        {
            title: '组织名称',
            dataIndex: 'namePath',
            copyable: true,
            ellipsis: true,
            hideInSearch: true,
            valueType: 'select',
            renderFormItem: (_, data, from) => {

                return (
                        <Select                        
                            options={orgNameOptions}
                            showSearch={true}
                            onSelect={onOrgNameSelect}
                            onSearch={(value) => getList('orgName', value)}
                            >
                        </Select>
                )
            },
            render: (_, data) => {
                return <div>{data.namePath}</div>
            }
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <a
                    key="editable"
                    onClick={() => {
                    action?.startEditable?.(record.id);
                    setOrgOptions([])
                    setOrgNameOptions([])
                    }}
                >
                    编辑
                </a>
            ],
        },

3、用到的方法

这里是两个onSelect以及获取下拉框数据,来自同一个接口
但为了区分数据回显的两个下拉框,因为一个是id一个是name的显示,所以我设置的两个Select的options数据value和label都分别是相同的,所以获取数据分了id和name的区别(还有个原因是我用官网的下拉搜索框的组件一直有点问题)

 // 获取下拉框数据
    const getList = debounce(((selectName: string, param: string| undefined)=> {
        // 组织名称筛选时-正则匹配获取参数最后的组织id
        var regex1 = /(?<=\()(.+?)(?=\))/g;; 
        if(param?.match(regex1) !== null ) {
           let res: string| undefined = param?.match(regex1)?.[0] 
           param = res
        }
        // 下拉框是组织id
        if(selectName == 'orgId') {
          return adminApi.getDept({searchDept: param}).then((response: any) => {
            // 当组织名称被选中,数据则只有一条
            if(response.data.length == 1) {
                console.log(tableForm.getFieldsValue());
                // 设置组织id名称变化
                tableForm.setFieldsValue({
                    [editableKeys[0] as number] : {
                        'orgId': response.data[0].value
                    }
                    
                })
              }
              response.data?.map((item: selectValueType) => {
                item.label = item.value
              })
              setOrgOptions(response.data)
              
            })
          }
          // 下拉框是组织名称
          if(selectName == 'orgName') {
            return adminApi.getDept({searchDept:param}).then((response: any) => {
                // 设置
                if(response.data.length == 1) {
                    tableForm.setFieldsValue({
                        [editableKeys[0] as number] : {
                            'namePath': response.data[0].label
                        }
                        
                    })
                  }
                response.data?.map((item: selectValueType) => {
                    item.value = item.label;
                  })
                setOrgNameOptions(response.data)
              })
            }
    }), 800)

    const onOrgIdSelect = async (selected: string) => {
        await getList('orgName', selected)
    }
    const onOrgNameSelect = async (selected: string) => {
        await getList('orgId', selected)
    }

踩到的坑

其中数据回显的使用,注意tableForm.setFieldsValue的使用
我之前就是一直在这里踩坑,一直回显不出来,后面打印了
tableForm.getFieldsValue()才知道,这个tableForm里面,因为外层是table包裹的form,而且编辑的是行,所以外层包裹了一层key值,我这里因为设置table的key值是id是个数字,所以是这样设置才生效了。

tableForm.setFieldsValue({
                    [editableKeys[0] as number] : {
                        'orgId': response.data[0].value
                    }
                    
                })

还有一些数据回显设置
比如 if(response.data.length == 1)
这里是因为是下拉搜索框,所以在我选择某一下拉框后,根据选中的value搜索另一个下拉框的值,因为二者是一一对应的关系,所以对应另一个下拉框也应该只有一个,所以直接设置另一个下拉框是第一个值

4、完整代码

import {DownloadOutlined, EllipsisOutlined, PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {
    ModalForm,
    ProForm,
    ProFormDateRangePicker,
    ProFormSelect,
    ProFormText,
} from '@ant-design/pro-components';
import {ProTable, EditableProTable,TableDropdown,} from '@ant-design/pro-components';
import {Button, Dropdown, Space, Tag, Form, message, Select, Divider, Popconfirm, Input} from 'antd';
import React, {SetStateAction, useEffect, useRef, useState} from 'react';
import request from 'umi-request';
import adminApi from "@/services/admin"; 
import {DefaultOptionType} from 'antd/es/select';
import {ProFormItem, ProFormItemProps} from "@ant-design/pro-form";
import {useModel} from "@@/exports";

import debounce from 'lodash/debounce';
export const waitTimePromise = async (time: number = 100) => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(true);
        }, time);
    });
};

export const waitTime = async (time: number = 100) => {
    await waitTimePromise(time);
};

type AdminAccountItem = {
    url: string;
    username: string;
    staffName: string;
    roleName: string;
    orgId: string;
    namePath: string;
    id: number;
    number: number;
    title: string;
    labels: {
        name: string;
        color: string;
    }[];
    state: string;
    comments: number;
    created_at: string;
    updated_at: string;
    closed_at?: string;
};

type saveAdminDataType = {
    roleId: string;
    staffId: string;
    orgId: string;
}

interface selectValueType {
    label: string;
    value: string;
}

export default () => {

    const [tableForm] = Form.useForm<AdminAccountItem>();



    const [listData, setListData] = useState<readonly AdminAccountItem[]>()
    const [exportParam, setExParam] = useState<AdminAccountItem>();

    // 组织id下拉框数据
    const [orgOptions, setOrgOptions] = useState<selectValueType[]>([]);
    // 组织名称下拉框数据
    const [orgNameOptions, setOrgNameOptions] = useState<selectValueType[]>([]);
    
 const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])
    // 获取下拉框数据
    const getList = debounce(((selectName: string, param: string| undefined)=> {
        // 组织名称筛选时-正则匹配获取参数最后的组织id
        var regex1 = /(?<=\()(.+?)(?=\))/g;; 
        if(param?.match(regex1) !== null ) {
           let res: string| undefined = param?.match(regex1)?.[0] 
           param = res
        }
        // 下拉框是组织id
        if(selectName == 'orgId') {
          return adminApi.getDept({searchDept: param}).then((response: any) => {
            // 当组织名称被选中,数据则只有一条
            if(response.data.length == 1) {
                console.log(tableForm.getFieldsValue());
                // 设置组织id名称变化
                tableForm.setFieldsValue({
                    [editableKeys[0] as number] : {
                        'orgId': response.data[0].value
                    }
                    
                })
              }
              response.data?.map((item: selectValueType) => {
                item.label = item.value
              })
              setOrgOptions(response.data)
              
            })
          }
          // 下拉框是组织名称
          if(selectName == 'orgName') {
            return adminApi.getDept({searchDept:param}).then((response: any) => {
                // 设置
                if(response.data.length == 1) {
                    tableForm.setFieldsValue({
                        [editableKeys[0] as number] : {
                            'namePath': response.data[0].label
                        }
                        
                    })
                  }
                response.data?.map((item: selectValueType) => {
                    item.value = item.label;
                  })
                setOrgNameOptions(response.data)
              })
            }
    }), 800)

    const onOrgIdSelect = async (selected: string) => {
        await getList('orgName', selected)
    }
    const onOrgNameSelect = async (selected: string) => {
        await getList('orgId', selected)
    }
    const columns: ProColumns<AdminAccountItem>[] = [
        {
            title: '组织ID',
            dataIndex: 'orgId',
            copyable: true,
            ellipsis: true,
            hideInSearch: true,
            valueType: 'select',
            renderFormItem: (_, data, form) => {
                return (
                        <Select
                            options={orgOptions}
                            showSearch={true}
                            onSelect={onOrgIdSelect}
                            onSearch={(value) => getList('orgId', value)}
                            >
                        </Select>
                )
            },
            render: (_, data) => {
                return <div>{data.orgId}</div>
            }
        },
        {
            title: '组织名称',
            dataIndex: 'namePath',
            copyable: true,
            ellipsis: true,
            hideInSearch: true,
            valueType: 'select',
            renderFormItem: (_, data, from) => {

                return (
                        <Select                        
                            options={orgNameOptions}
                            showSearch={true}
                            onSelect={onOrgNameSelect}
                            onSearch={(value) => getList('orgName', value)}
                            >
                        </Select>
                )
            },
            render: (_, data) => {
                return <div>{data.namePath}</div>
            }
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <a
                    key="editable"
                    onClick={() => {
                    action?.startEditable?.(record.id);
                    setOrgOptions([])
                    setOrgNameOptions([])
                    }}
                >
                    编辑
                </a>
            ],
        },
    ];
    
    
   

    return (

        <EditableProTable<AdminAccountItem>
            columns={columns}
            actionRef={actionRef}
            cardBordered
            form={tableForm}
            request={async (params = {}, sort, filter) => {
                console.log(sort, filter);
                // await waitTime(2000);
                setExParam(params as unknown as AdminAccountItem);
                return request<{
                    data: AdminAccountItem[];
                }>('getAdminAccount', {
                    params,
                }).then(res => {
                    setListData(res.data)
                    return res
                });
            }}

            editable={{
                form: tableForm,
                editableKeys,
                // type: 'multiple',
                onSave: async (rowKey, data, row) => {
                    console.log('row', data);
                    await adminApi.updateAdmin(data)
                  },
                onCancel:async () => {
                    
                },
                onChange: setEditableRowKeys,
                // 设置编辑只留保存和取消按钮
                actionRender: (row, config, dom) => [dom.save, dom.cancel],
              }}
            value={listData}
            onChange={setListData}
            columnsState={{
                persistenceKey: 'pro-table-singe-demos',
                persistenceType: 'localStorage',
                onChange(value) {
                    console.log('value: ', value);
                },
            }}
            rowKey="id"
            search={{
                labelWidth: 'auto',
            }}
            options={{
                setting: {
                    listsHeight: 400,
                },
            }}

            form={{
                // 由于配置了 transform,提交的参与与定义的不同这里需要转化一下
                syncToUrl: (values, type) => {
                    if (type === 'get') {
                        return {
                            ...values,
                            created_at: [values.startTime, values.endTime],
                        };
                    }
                    return values;
                },
            }}
            pagination={{
                pageSize: 10,
                onChange: (page) => console.log(page),
            }}
            dateFormatter="string"
            headerTitle="管理员列表"
        >
        </EditableProTable>

    );
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1116797.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

059:mapboxGL监听键盘事件,通过eastTo控制左右旋转

第059个 点击查看专栏目录 本示例是介绍演示如何在vue+mapbox中监听键盘事件,通过eastTo控制左右旋转。 本例通过easeTo方法来加减一定数值的bearing角度,通过.addEventListener的方法来监听键盘的按键动作。这里一定要设置interactive: false, 否则展现不出来旋转效果。 直…

小微企业低成本获客攻略,媒介盒子无偿分享

品牌推广已经成为企业获客的主要手段&#xff0c;品牌推广能够使企业将自身的品牌、产品信息传递到受众面前&#xff0c;但是小微企业在公司成立之初往往资金有限&#xff0c;那么小微企业如何用低成本精准获客呢&#xff1f;可以试试软文。接下来媒介盒子就告诉大家&#xff0…

IO入门day1

课程分为三部分&#xff1a;IO文件-动态库、静态库制作&#xff0c;进程&#xff08;本地进程间通信&#xff09;&#xff0c;线程&#xff08;线程通信&#xff09; 特点&#xff1a;学习大量的函数接口调用-函数名及功能、man手册查看参数 一、IO介绍 1、概念 对文件的输入输…

Vue3中使用富文本编辑器

在vue3中我们可以使用wangeditor/editor、wangeditor/editor-for-vue来实现其功能 npm地址&#xff1a;https://www.npmjs.com/package/wangeditor/editor-for-vue/v/5.1.12?activeTabreadme 官网&#xff1a;Editor 1. 安装 pnpm add wangeditor/editor # 或者 npm inst…

ESRI ArcGIS Desktop 10.8.2图文安装教程及下载

ArcGIS 是由美国著名的地理信息系统公司 Esri 开发的一款地理信息系统软件&#xff0c;它是目前全球最流行的 GIS 软件之一。ArcGIS 提供了图形化用户界面和数据分析工具&#xff0c;可以帮助用户管理、分析和可视化各种空间数据。ArcGIS Desktop是一个完整的桌面GIS软件套件&a…

2023“龙芯杯”信创攻防赛 | 赛宁网安技术支持

2023年10月19日&#xff0c;为深入贯彻国家网络强国战略思想&#xff0c;宣传国家网络安全顶层设计&#xff0c;落实《网络安全法》《数据安全法》等法律法规。由大学生网络安全尖锋训练营主办&#xff0c;龙芯中科技术股份有限公司承办&#xff0c;山石网科通信技术股份有限公…

解决XXLJOB重复执行问题--Redis加锁+注解+AOP

基于Redis加锁注解AOP解决JOB重复执行问题 现象解决方案自定义注解定义AOP策略redis 加锁实践 现象 线上xxljob有时候会遇到同一个任务在调度的时候重复执行&#xff0c;如下图&#xff1a; 线上JOB服务运行了2个实例&#xff0c;有时候会重复调度到同一个实例&#xff0c;有…

【标准化封装 SOT系列 】 B SOT-223

SOT-223 pin 间距 2.3mm 名称pin 数厂家 body DE矩形 (mm)SOT-2234ADI – LTC196 . 6.3/6.71*3.3/3.71

基于广义正态分布优化的BP神经网络(分类应用) - 附代码

基于广义正态分布优化的BP神经网络&#xff08;分类应用&#xff09; - 附代码 文章目录 基于广义正态分布优化的BP神经网络&#xff08;分类应用&#xff09; - 附代码1.鸢尾花iris数据介绍2.数据集整理3.广义正态分布优化BP神经网络3.1 BP神经网络参数设置3.2 广义正态分布算…

接口测试 Jmeter 接口测试 —— 请求 Headers 与传参方式

一、 背景&#xff1a; 在使用 Jmeter 进行接口测试时&#xff0c;有些小伙伴不知道 Headers 和请求参数 (Parameters&#xff0c;Body Data) 的联系&#xff0c;本文主要讲 Content-Type 为 application/x-www-form-urlencoded 和 application/json 的场景。 1、使用 Parame…

Cesium Vue(七)— GEOJSON数据展示

1. GeoJSON GeoJSON 是一种用于对各种地理数据结构进行编码的格式。 简而言之&#xff0c;GeoJSON为你提供了一种简单的格式来表示简单的地理特征以及它们的非空间属性。 结构&#xff1a; {"type": "Feature","geometry": {"type"…

交叉熵(crossentropy)损失

1 神经网络分类问题 分类问题&#xff0c;通常分为二分类问题与多分类问题&#xff08;大于2类&#xff09;。 2 二分类问题 2.1 网络设计 神经网络的最后一层&#xff08;输出层&#xff09;&#xff0c;为一个神经元&#xff0c;使用激活函数sigmoid。 tf.keras.layers.…

如何测试WordPress能否成功发送邮件

如果你的WordPress网站没有连接到SMTP服务器&#xff0c;就发不了邮件。 修改管理员密码&#xff0c;发不了邮件。 用户提交表单&#xff0c;你收不到邮件提醒。 确定真的需要配置SMTP 有的服务器在一键安装WordPress的时候&#xff0c;已经帮你配置好了&#xff08;比如Sit…

windos默认输入法开机无法使用,需要手动执行ctfmon.exe

windos默认输入法开机无法使用&#xff0c;需要手动执行ctfmon.exe 系统&#xff1a;win10专业版 第一种方法 以管理员身份运行cmd 执行 sfc /scannow 1.右键点击此电脑&#xff0c;点击管理&#xff0c;打开如图所示服务选项卡&#xff0c;找到如图所示服务点击启动&#…

数据结构与算法(十):动态规划与贪心算法

参考引用 Hello 算法 Github&#xff1a;hello-algo 1. 动态规划算法 动态规划将一个问题分解为一系列更小的子问题&#xff0c;并通过存储子问题的解来避免重复计算&#xff0c;从而大幅提升时间效率 问题&#xff1a;给定一个共有 n 阶的楼梯&#xff0c;你每步可以上 1 阶或…

Django和jQuery,实现Ajax表格数据分页展示

1.需求描述 当存在重新请求接口才能返回数据的功能时&#xff0c;若页面的内容很长&#xff0c;每次点击一个功能&#xff0c;页面又回到了顶部&#xff0c;对于用户的体验感不太友好&#xff0c;我们希望当用户点击这类的功能时&#xff0c;能直接加载到数据&#xff0c;请求…

C#,数值计算——分类与推理Phylagglomnode的计算方法与源程序

1 文本格式 using System; using System.Collections.Generic; namespace Legalsoft.Truffer { public class Phylagglomnode { public int mo { get; set; } public int ldau { get; set; } public int rdau { get; set; } public …

# 用acme.sh申请证书(含泛域名)

用acme.sh申请证书&#xff08;含泛域名&#xff09; 文章目录 用acme.sh申请证书&#xff08;含泛域名&#xff09;1 申请证书&#xff1a;1.1 使用dns api方式申请证书&#xff08;以阿里云dns为例&#xff09;1.2 附加&#xff1a;也可以用其他方式申请证书 2 续签证书&…

跨域方案的抉择

前言 遇到跨域问题的时候&#xff0c;到底是使用CORS来解决&#xff0c;还是使用代理呢&#xff1f; 判断依据不是技术层面&#xff0c;而是你的生产环境。 首先要关注的是生产环境里面到底是一种什么样的情况&#xff0c;到底有没有跨域&#xff0c;然后根据生产环境的情况&a…

yjs demo: 多人在线协作画板

基于 yjs 实现实时在线多人协作的绘画功能 支持多客户端实时共享编辑自动同步&#xff0c;离线支持自动合并&#xff0c;自动冲突处理 1. 客户端代码&#xff08;基于Vue3&#xff09; 实现绘画功能 <template><div style"{width: 100vw; height: 100vh; over…