import { EditableProTable } from '@ant-design/pro-components';
import { useEffect, useState } from 'react';
const EditModal = ()=>{
const editableFormRef = useRef();
const [tableData, setTableData] = useState<TableDataType[]>([]);
const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
const tableColumns: any = [
{
title: '到货量(起)',
dataIndex: 'productCountStart',
valueType: 'digit',
fieldProps: {
min: 1,
precision: 0,
style: { width: '90%' },
},
formItemProps: () => {
return {
rules: [{ required: true }],
};
},
},
{
title: '到货量(止)',
dataIndex: 'productCountEnd',
valueType: 'digit',
fieldProps: {
min: 1,
precision: 0,
style: { width: '90%' },
},
formItemProps: () => {
return {
rules: [{ required: true }],
};
},
},
{
title: '最小质检量',
dataIndex: 'minQualityCheckNum',
valueType: 'digit',
fieldProps: {
min: 1,
precision: 0,
style: { width: '90%' },
},
formItemProps: () => {
return {
rules: [{ required: true }],
};
},
},
{
title: '操作',
valueType: 'option',
width: 150,
render: (text, record, _, action) => (
<>
<Button
type="link"
size="small"
onClick={() => {
action?.startEditable?.(record.id);
}}
>
编辑
</Button>
<Popconfirm
title="已保存数据,是否确认删除"
cancelText="取消"
okText="确定"
onConfirm={() =>
setTableData(tableData.filter((item) => item.id !== record.id))
}
>
<Button size="small" type="link">
删除
</Button>
</Popconfirm>
</>
),
},
];
const onSave = () => {
const values = formRef.current?.getFieldsValue();
if (editableKeys.length) {
return message.warning('请先保存再提交');
}
if (!tableData.length) return message.warning('请添加');
API.add(values).then(() => {
message.success('保存成功');
});
};
useEffect(() => {
if (id) {
Api.getList({ id }).then(({ data }) => {
setTableData(data || []);
});
}
}, [id]);
return (
<EditableProTable
rowKey="id"
editableFormRef={editableFormRef}
columns={tableColumns}
value={tableData}
onChange={setTableData}
recordCreatorProps={{
record: () => ({ id: (Math.random() * 1000000).toFixed(0) }),
}}
editable={{
type: 'single',
editableKeys,
onChange: setEditableRowKeys,
}}
style={{
maxHeight: 500,
overflow: 'hidden',
overflowY: 'scroll',
}}
/>
)
}
1、表单联动
fieldProps:(form, { entity = {}, rowIndex }) => {
return {
onChange: (val) => {
editableFormRef.current?.setRowData?.(rowIndex, {
otherVal: 1,//控制另一个表单项otherVal
});
},
}
}
formItemProps: (form, {entity}) => {
return {
rules: [
{ required: !!entity.otherVal, message: '请输入' },//otherVal有值此项必填
],
};
},
//或者放在render
render: (_, row, index) => {
<Button
type="primary"
onClick={() => {
editableFormRef.current?.setRowData?.(index, {
otherVal: 1,
});
}}
>
点击
</Button>
}