基于antd@5.x封装Form.List组件
使用案例
const initFormState = {
formList1: [
{
start: '测试',
end: '100',
},
{
start: 'abc',
end: 'value',
},
],
formList2: [
{
start: '测试2',
end: '6',
},
{
start: 'vxcv',
end: 'jksdhfjk',
},
],
};
<Form
form={form}
onFinish={onFinish}
autoComplete='off'
initialValues={initFormState}
>
<FormList
name='formList1'
rules={[
{
validator(_, names) {
if (!names || !names.length) {
return Promise.reject(new Error('至少填写一组数据!'));
}
return Promise.resolve();
},
},
]}
dataSource={[
{
label: 'start', name: 'label',
component: <Input />,
rules: [{ required: true, message: '请输入' }],
},
{ label: 'end', name: 'value', component: <Input /> },
]}
/>
<FormList
name='formList2'
dataSource={[
{ label: 'start', name: 'label', component: <Input /> },
{ label: 'end', name: 'value', component: <Input /> },
]}
/>
<Form.Item>
<Button type='primary' htmlType='submit'>
Submit
</Button>
</Form.Item>
</Form>
import React from 'react';
import { Form, Button, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { IPropsType } from './interface';
function FormList(props: IPropsType & typeof Form.List) {
const { addText, addHidden, addDisabled, dataSource, name, ...otherFormListProps } = props;
return (
<Form.List name={name} {...otherFormListProps}>
{(fields, { add, remove }) => {
return (
<>
{fields.map(({ key, name: fieldName, ...restField }) => (
<div key={key}>
<Space align='baseline'>
{dataSource.map(
({ label, name: itemName, component, ...formItem }, idx) => {
return (
<Form.Item
key={idx}
{...restField}
label={label}
name={[fieldName, itemName]}
{...formItem}
>
{component}
</Form.Item>
);
},
)}
<MinusCircleOutlined onClick={() => remove(fieldName)} />
</Space>
</div>
))}
{!addHidden && (
<Form.Item>
<Button
type='dashed'
disabled={addDisabled}
onClick={() => add()}
block
icon={<PlusOutlined />}
>
{addText}
</Button>
</Form.Item>
)}
</>
);
}}
</Form.List>
);
}
FormList.defaultProps = {
addText: '新增',
addHidden: false,
addDisabled: false,
dataSource: [],
name: '',
};
export default FormList;
import React from 'react';
interface IDataSourceType {
name: string;
label?: string | React.ReactNode | undefined;
component: React.ReactNode;
}
export interface IPropsType {
/**
* 新增按钮文案 String | ReactNode
*/
addText: string | React.ReactNode;
/**
* 新增按钮是否隐藏 Boolean
*/
addHidden: boolean;
addDisabled: boolean;
/**
* 循环重复表单项
*/
dataSource: IDataSourceType[];
/**
* Form.List 绑定字段
*/
name: string;
}