Ant Design Pro Table 编辑弹窗:实现全列编辑功能
Ant Design Pro Table 编辑弹窗:实现全列编辑功能
本文介绍了如何使用 Ant Design Pro Table 实现编辑弹窗功能,并提供了一种方法让表格的每一列在弹窗打开时处于编辑状态。
代码示例:
import { ModalForm } from '@ant-design/pro-form';
import { ActionType, EditableProTable, ProColumns } from '@ant-design/pro-table';
import React, { useEffect, useRef, useState } from 'react';
import { getOnlyKey } from '@/utils/utils';
import { Button, Radio, RadioChangeEvent, Space, message } from 'antd';
import { PlusCircleOutlined } from '@ant-design/icons';
import { getProjectList, getSave } from '@/services/project/new/built';
import { useModel } from 'umi';
import { isArray } from 'lodash';
import { TYPE_PROJECT } from '@/constant/new';
import { getUserList } from '@/services/project/home/index';
interface Props {
children: React.ReactElement;
refresh: () => void;
}
interface ListItem {
projectName: string;
projectChip: string;
projectType: string;
publicTime: string;
id: string;
releaseTime: string;
rowIndex: string;
}
const ModalFocus: React.FC<React.PropsWithChildren<Props>> = (props) => {
const { children, refresh } = props;
const [visible, setVisible] = useState<boolean>(false);
const actionRef = useRef<ActionType>();
const { initialState } = useModel('@@initialState');
const { currentUser } = initialState || {};
const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
const [focusData, setFocusData] = useState<any>([]);
const [selectOptions, setSelectOptions] = useState<ProjectInfoDetail[]>([]);
const [redioValue, setRedioValue] = useState('');
/*** 获取项目列表*/
const getProjectOptions = async () => {
try {
const { data } = await getProjectList({
projectStatuses: ['PROGRESSING', 'INIT', 'PAUSED', 'FINISH'],
createBy: currentUser?.userName || '',
userId: currentUser?.userId || '',
});
if (!isArray(data)) throw new Error('暂无已建项目列表!');
setSelectOptions(data);
} catch (error) {
setSelectOptions([]);
}
};
/***列表*/
const getUser = async () => {
try {
const { data } = await getUserList({ oaName: initialState?.currentUser?.userName });
setFocusData(data);
// const newId = getOnlyKey();
// data.push({ id: newId });
setEditableRowKeys(data.map((it:any)=>{it.id}));
} catch (error) {}
};
useEffect(() => {
getProjectOptions();
getUser();
}, []);
const valueChange = (e: RadioChangeEvent) => {
setRedioValue(e.target.value);
};
const columns: ProColumns<ListItem>[] = [
{
dataIndex: 'index',
valueType: 'indexBorder',
width: 50,
},
{
title: '机芯',
dataIndex: 'chip',
align: 'center',
readonly: true,
},
{
title: '项目ID',
dataIndex: 'projectId',
align: 'center',
readonly: true,
width: 100,
},
{
title: '软件项目名称',
dataIndex: 'projectName',
valueType: 'select',
readonly: false,
fieldProps: (text: string, record: ListItem) => {
return {
fieldNames: { label: 'projectName', value: 'id' },
options: selectOptions,
onChange: (value: string, option: any) => {
console.log(option, 100);
const { projectChip, id, projectType, projectName } = option;
const currentRowIndex = record.rowIndex;
const currentRowData = focusData[currentRowIndex];
const updatedRowData = {
...currentRowData,
chip: projectChip,
projectType,
projectId: id,
projectName,
oaName: initialState?.currentUser?.userName,
};
const updatedFocusData = [...focusData];
updatedFocusData[currentRowIndex] = updatedRowData;
setFocusData(updatedFocusData);
setEditableRowKeys([...editableKeys, id]);
},
};
},
},
{
title: '项目类型',
dataIndex: 'projectType',
readonly: true,
align: 'center',
width: 120,
valueEnum: TYPE_PROJECT,
},
{
title: '操作',
dataIndex: 'opeation',
valueType: 'option',
width: 140,
renderFormItem: (text, record, _, action) => {
return (
<Radio.Group value={redioValue} onChange={valueChange}>
<Radio value={1}>已关注</Radio>
<Radio value={0}>已取消关注</Radio>
</Radio.Group>
);
},
},
];
const handleSave = async () => {
try {
const updatedFocusData = focusData.map((item: any) => ({
...item,
id: undefined,
deleted: redioValue, // 将 redioValue 值赋给 deleted 字段
}));
const { code, msg } = await getSave({ userCareProjectList: updatedFocusData });
if (code !== 100000) throw new Error(msg);
message.success('保存成功');
setVisible(false);
if (refresh) refresh();
} catch (error) {}
};
return (
<>
{React.cloneElement(children, {
onClick: () => {
setVisible(true);
setEditableRowKeys(focusData.map((it:any)=>{it.id})); // 在弹窗打开时设置 editableKeys
},
})}
<ModalForm
title='我关注的项目'
visible={visible}
submitter={{
searchConfig: {
submitText: '保存',
resetText: '取消',
},
render: (_, dom) => <Space>{dom}</Space>,
submitButtonProps: {
onClick: handleSave, // 点击保存按钮时调用 handleSave 函数
},
}}
modalProps={{
destroyOnClose: true,
onCancel: () => {
setVisible(false);
setFocusData([]);
setRedioValue('');
},
}}
layout='horizontal'
>
<EditableProTable
value={focusData}
columns={columns}
actionRef={actionRef}
rowKey='id'
recordCreatorProps={false}
editable={{
type: 'multiple',
editableKeys,
onChange: setEditableRowKeys,
actionRender: (row, config, defaultDoms) => {
return [];
},
}}
onChange={(dataSource) => {
const newData = dataSource.map((item, rowIndex) => {
const rowData = focusData.find((row: any) => row.id === item.id) || {};
return {
...rowData,
...item,
};
});
setFocusData(newData);
}}
/>
<Space>
<Button
style={{ border: '1px' }}
onClick={() => {
const data = [...focusData];
const newId = getOnlyKey();
data.push({ id: newId });
setFocusData(data);
setEditableRowKeys([...editableKeys, newId]);
}}
>
<PlusCircleOutlined />
</Button>
</Space>
</ModalForm>
</>
);
};
export default React.memo(ModalFocus);
解释:
- 在打开弹窗时,将
editableKeys设置为当前数据中所有行的id,这样就可以让表格的每一行都处于编辑状态了。具体可以在setVisible(true)后添加以下代码:
setEditableRowKeys(focusData.map((it:any)=>{it.id}));
EditableProTable组件的editable属性中,editableKeys用于控制哪些行处于可编辑状态。当editableKeys包含所有行的id时,所有行都处于可编辑状态。
注意:
- 确保
focusData中的所有行都有唯一的id。 - 可以使用其他方法来获取所有行的
id,例如focusData.map((item) => item.id)。
希望以上代码和解释能够帮助您实现 Ant Design Pro Table 的全列编辑功能!
原文地址: https://www.cveoy.top/t/topic/omUe 著作权归作者所有。请勿转载和采集!