目前只配置了输入框和文本框,需要的可自定义添加type
const initValues = [
{type:'input',name:'start',label:'最小值',initValue:'',},
{type:'input',name:'end',label:'最大值',initValue:'',},
{type:'text',name:'unit',label:'采购单位',initValue:'盒',rules:[]},
{type:'input',name:'unitPrice',label:'单价(含税)',initValue:'',},
{type:'input',name:'platformUnitPrice',label:'销售单价(含税)',initValue:'',},
]
import { Form, Input, Button, Space, Select } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import React from "react";
const formItemLayout = {
labelCol: {span: 24},
wrapperCol: {span: 24},
};
const areas = [
{label: 'Beijing', value: 'Beijing'},
{label: 'Shanghai', value: 'Shanghai'},
];
const initRules = [{required: true, message: '字段必填!'}]
interface FormItemProps {
type: string,
name: string;
label: string;
initValue: string;
rules: {}[]
}
interface TypeProps {
initValues: FormItemProps[]
}
const FormList = (props: TypeProps) => {
const {initValues} = props;
console.log(initValues)
const [form] = Form.useForm();
const onFinish = values => {
console.log('Received values of form:', values);
};
const handleChange = () => {
form.setFieldsValue({sights: []});
};
return (
<Form form={ form } name="dynamic_form_nest_item" onFinish={ onFinish } autoComplete="off">
<Form.Item name="area" label="Area" rules={ [{required: true, message: 'Missing area'}] }>
<Select options={ areas } onChange={ handleChange }/>
</Form.Item>
<Form.List name="sights">
{ (fields, {add, remove}) => (
<>
{ fields.map(field => (
<Space key={ field.key } align="baseline">
{ initValues.map(item => (
<Form.Item
{ ...field }
label={ item.label }
{ ...formItemLayout }
name={ [field.name, item.name] }
fieldKey={ [field.fieldKey, item.name] }
rules={ item.rules || initRules }
initialValue={ item.initValue }
>
{ item.type === 'text' ? item.initValue : <Input/> }
</Form.Item>
)) }
<MinusCircleOutlined onClick={ () => remove(field.name) }/>
</Space>
)) }
<Form.Item>
<Button type="dashed" onClick={ () => add() } block icon={ <PlusOutlined/> }>
Add sights
</Button>
</Form.Item>
</>
) }
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
export default FormList
参考来源