这次给大家分享一个封装的新增+编辑的可复用组件,如果公司比较忙,崔的紧可以是使用这个组件,使用antd官网给的例子需要自己去修改一些值,封装这个组件的意义就在于,平常可以直接使用这个组件,像table的columns的方式传值,渲染展示,不仅传值方便,操作也比较方便。
import { NpTableContext } from '@/components/CustomTable';
import { userName } from '@/utils/Regex';
import { FormOutlined, PlusOutlined } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-form';
import {
ModalForm,
ProFormDatePicker,
ProFormSelect,
ProFormText,
ProFormTextArea,
ProFormCascader,
ProFormSwitch,
ProFormDigit
} from '@ant-design/pro-form';
import { Button, message, Popover } from 'antd';
import { useContext, useRef } from 'react';
import styleContent from './index.less';
css.{
//可创建一个文件引入进去
@import '~antd/es/style/themes/default.less';
.content {
:global(.ant-form) {
display: flex;
flex-wrap: wrap;
}
:global(.ant-form-item) {
padding-left: 10px !important;
}
}
}
type UpdateFormProps = {
recordItem?: any | []; //编辑返现,非必传,但是编辑如果要做返现,是必传
title?: string; //传值->‘add’||‘update’,是告诉组件,引用的是编辑还是新增,必传
formItemList: any;//这里就是要渲染组件的数组,必传
update: (params: any) => Promise<{ success: boolean }>;//这里传add或者update的接口,必传
};
//最底部会贴出一个使用方法
const BaseModalForm = (props: UpdateFormProps) => {
const { recordItem, title, formItemList, PageCode, initialState, update, } = props;
const restFormRef = useRef<ProFormInstance>();//这个是from表单的ref方法
const { actionRef } = useContext(NpTableContext);//这里是刷新table的,点击确定后可以直接获取table的接口,可以去看下小编的之前的一篇文章封装protable:封装ProTable组件__琉的博客-CSDN博客
const propsfrom = () => {
const formList: any = [];
if (formItemList && formItemList.length > 0) {
formItemList.map((item: any, index: number) => {
const { name, label, width = 'sm', disabled = false, rules = false, options = [], optionType = [],
modes = '', } = item;
if (item.option === 'userText' && item.patterns.pattern === userName) {
const userText = (
<ProFormText
key={item.id || index}
width={width}
name={name}
label={label}
disabled={disabled}
rules={rules === true ? [{ required: true, message: '这是必填项' }] : []}
fieldProps={{
onChange: (value: any) => {
const text = value?.target?.value;
if (/[\u4E00-\u9FA5]/g.test(text)) {
restFormRef.current?.setFieldsValue({
userName: text.replace(/[\u4E00-\u9FA5]/g, ''),
});
} else {
restFormRef.current?.setFieldsValue({ userName: text.toLowerCase() });
}
},
autoComplete: 'off',
}}
/>
);
formList.push(userText);
} else if (item.option === 'text') {
const text = (
<ProFormText
key={item.id || index}
width={width}
name={name}
label={label}
disabled={disabled}
rules={[
{ required: rules, message: '这是必填项' },
item.patterns
? { pattern: item.patterns.pattern, message: item.patterns.message }
: {},
]}
fieldProps={{
autoComplete: 'off',
}}
/>
);
formList.push(text);
} else if (item.option === 'ProFormSelect') {
const Select = (
<ProFormSelect
key={item.id || index}
width={width}
name={name}
label={label}
fieldProps={{
mode: modes,
options: optionType,
}}
placeholder="请选择"
rules={[{ required: rules, message: '请选择!' }]}
/>
);
formList.push(Select);
} else if (item.option === 'ProFormTextArea') {
const textArwa = (
<ProFormTextArea
key={item.id || index}
width={width}
name={name}
label={label}
placeholder="请输入"
/>
);
formList.push(textArwa);
} else if (item.option === 'ProFormDatePicker') {
const DatePicker = (
<ProFormDatePicker rules={[{ required: rules, message: '请选择!' }]} key={item.id || index} name={name} label={label} width={width} />
);
formList.push(DatePicker);
} else if (item.option === 'ProFormCascader') {
const Cascader = (
<ProFormCascader
key={item.id || index}
width={width}
name={name}
label={label}
fieldProps={{
options: options,
}}
/>
);
formList.push(Cascader);
} else if (item.option === 'ProFormSwitch') {
const Switch = (
<ProFormSwitch
key={item.id || index}
width={width}
name={name}
label={label} />
);
formList.push(Switch);
} else if (item.option === 'ProFormDigit') {
const Digit = (
<ProFormDigit
width={width}
key={item.id || index}
label={label}
name={name}
min={0}
rules={[{ required: rules, message: '请输入!' }]}
fieldProps={{ precision: 0 }}
/>
);
formList.push(Digit);
}
});
}
return formList;
};
const onVisibleChange = (visible: boolean) => {
restFormRef?.current?.resetFields();
};
return !enabled ? <></> : (
<ModalForm
onVisibleChange={onVisibleChange}
width={512}
initialValues={recordItem}
modalProps={{
centered: true,
className: styleContent.content,
}}
formRef={restFormRef}
title={title === 'add' ? '新增' : '编辑'}
trigger={
title === 'update' ? (
<Popover content="编辑" placement="rightTop" trigger="hover">
<FormOutlined style={{ color: '#1890FF' }} />
</Popover>
) : (
<Button key="button" disabled={!enabled} type="primary" icon={<PlusOutlined />}>
新增
</Button>
)
}
submitter={
title === 'update'
? {
searchConfig: {
resetText: '重置',
},
resetButtonProps: {
onClick: () => {
onVisibleChange(true);
},
},
}
: {}
}
onFinish={async (values) => {
let res: any = {};
if (title === 'add') {
res = await update(values);
} else {
//这一步是编辑的时候拿到编辑行的数据,valeus的值就是可编辑的数据,循环recordItem的每一项并修改值,但是这样做是提交了整个一个编辑行的数据,使用的人可以根据规则进行修改,
//可修改成 const obj={
...values,
id: recordItem.id,
}
for (const key in recordItem) {
if (values.recordItem(key)) {
selectedDevice[key] = values[key];
}
}
obj 和recordItem传一个进去,具体传那个需要根据自己项目制定的规则去传
res = await update(obj || recordItem);
}
if (res.success) {
message.success('更新成功!');
restFormRef?.current?.resetFields();
restFormRef.current?.validateFields();
actionRef?.current?.reload();
return true;
}
throw new Error('更新失败');
}}
>
{propsfrom()}
</ModalForm>
);
};
export default BaseModalForm;
BaseModalForm组件使用方法:
name:传给后端的字段名;
label:组件title;
width:组件宽度,可设置number类型,也可设置官网给的例子;
option:组件的类型[ 'userText{做的有正则限制}',
'text',
'ProFormDatePicker',
'ProFormSelect',
'ProFormTextArea',
'ProFormText',
'ProFormCascader',
'ProFormSwitch',
'ProFormDigit'
];
disabled:是否禁用;
rules:是否必传
const formItemList = [
{
name: 'name',
label: '名称',
width: 'sm',
option: 'text',
disabled: false,
rules: true
},
{
name: 'code',
label: '代码',
width: 'sm',
option: 'text',
disabled: false,
},
{
name: 'warehouseId',
label: '仓库',
width: 'sm',
option: 'ProFormSelect',
disabled: false,
optionType: resourceData//搜索框传入的数组[{label:'',value:''}],
rules: true
},
{
name: 'projectType',
label: '项目类型',
width: 'sm',
option: 'ProFormSelect',
disabled: false,
optionType: [{
label: 'KLT',
value: 'KLT'
}, {
label: 'GLT',
value: 'GLT'
}],
rules: true
},
{
name: 'type',
label: '产线类型',
width: 440,
option: 'ProFormSelect',
disabled: false,
optionType: [{
label: '流水线',
value: 'LINE'
}, {
label: '工作岛',
value: 'ISLAND'
}],
rules: true
},
{
name: 'description',
label: '描述',
width: 440,
option: 'ProFormTextArea',
disabled: false,
},
]
const tableAttribute = {
title:'updata',//这里以编辑为例子
recordItem:recordItem,//这里是编辑行的数据,如果是新增可以不用传
formItemList:formItemList,//这里是需要渲染的组件
update: (params: Partial<User.Update>) => generalAccountRequest.update(params),
}
<BaseModalForm {...tableAttribute}/>