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

编程入门 行业动态 更新时间:2024-10-24 10:17:38

关于antdpro的EdittableProTable编辑时两个下拉搜索框的<a href=https://www.elefans.com/category/jswz/34/1771445.html style=数据联动以及数据回显(以及踩坑)"/>

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

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

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

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

最后是试出来的方式。

1、使用antdpro的EdittableProTable

<EditableProTable<AdminAccountItem>columns={columns}actionRef={actionRef}cardBorderedform={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 (<Selectoptions={orgOptions}showSearch={true}onSelect={onOrgIdSelect}onSearch={(value) => getList('orgId', value)}></Select>)},render: (_, data) => {return <div>{dataId}</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) => [<akey="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)=> {// 组织名称筛选时-正则匹配获取参数最后的组织idvar regex1 = /(?<=\()(.+?)(?=\))/g;; if(param?.match(regex1) !== null ) {let res: string| undefined = param?.match(regex1)?.[0] param = res}// 下拉框是组织idif(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)=> {// 组织名称筛选时-正则匹配获取参数最后的组织idvar regex1 = /(?<=\()(.+?)(?=\))/g;; if(param?.match(regex1) !== null ) {let res: string| undefined = param?.match(regex1)?.[0] param = res}// 下拉框是组织idif(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 (<Selectoptions={orgOptions}showSearch={true}onSelect={onOrgIdSelect}onSearch={(value) => getList('orgId', value)}></Select>)},render: (_, data) => {return <div>{dataId}</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) => [<akey="editable"onClick={() => {action?.startEditable?.(record.id);setOrgOptions([])setOrgNameOptions([])}}>编辑</a>],},];return (<EditableProTable<AdminAccountItem>columns={columns}actionRef={actionRef}cardBorderedform={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>);
};

更多推荐

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

本文发布于:2023-12-07 01:45:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1669696.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   编辑   两个   antdpro   EdittableProTable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!