基于antd@5.x封装Form.List组件文章来源:https://www.toymoban.com/news/detail-601195.html
使用案例文章来源地址https://www.toymoban.com/news/detail-601195.html
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;
}
到了这里,关于基于antd@5.x封装Form.List组件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!