useDynamicList官网
Demo
Dynamic
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { useDynamicList } from 'ahooks';
import { Button, Form, Input } from 'antd';
import React from 'react';
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
export default (props) => {
const { initialValue } = props
const { list, remove, getKey, push } = useDynamicList(initialValue ? initialValue : ['']);
const Row = (index: number, item: any) => (
<div key={getKey(index)} style={{ position: 'relative' }}>
<Form.Item
{...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
name={['users', index]}
label={index === 0 ? '名称' : ''}
initialValue={item}
>
<Input
style={{ width: 300 }}
placeholder="Please enter name"
/>
</Form.Item>
{list.length > 1 && (
<MinusCircleOutlined
style={{ marginLeft: 8, position: 'absolute', top: '10px', left: '70%' }}
onClick={() => {
remove(index);
}}
/>
)}
</div>
);
return (
<>
{list.map((ele, index) => Row(index, ele))}
<Form.Item>
<Button type='dashed'
onClick={() => {
push('')
}}
icon={<PlusOutlined />}>
添加一行
</Button>
</Form.Item>
</>
);
};
index
import { Button, Form, } from 'antd';
import React, { useEffect, useState } from 'react';
import Dynamic from './Dynamic';
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
export default () => {
return (
<>
<Form
autoComplete='off'
{...formItemLayoutWithOutLabel}
style={{ maxWidth: 600 }}
onFinish={(val) => {
console.log('val', val)
}}>
<Dynamic initialValue={['Jarry', 'John']} />
<Form.Item>
<Button htmlType='submit' type='primary'>提交</Button>
</Form.Item>
</Form>
</>
);
};
效果图
