?项目目录结构
?
1、app.js
import FormCom from './components/FormCom'
import './App.css'
function App() {
const items = [
{
type: 'Input',
label: '部门名称',
name: 'name',
rules: [{ required: true }]
},
{
type: 'Select',
label: '行政区划',
name: 'cityCode',
rules: [{ required: true }],
options: [
{ label: '北京', value: 156120000 },
{ label: '天津', value: 156130000 },
{ label: '上海', value: 156140000 }
]
},
{
type: 'DatePicker',
label: '创建时间',
name: 'createTime',
rules:[{ required: true}],
}
];
return (
<div className="App">
<FormCom items={items}/>
</div>
);
}
export default App;
2、FormCom.js
import React from 'react'
import { Form, Button } from 'antd'
import InputElem from './InputElem'
import SelectElem from './SelectElem'
import DatePickerElem from './DatePickerElem'
const FormCom = (props) => {
const { items } = props;
const [form] = Form.useForm();
// 检测是否存在标单项
if (!items || (items && items.length === 0)) {
return null;
}
const formItems = items.map(item => {
const { type, name } = item;
let Component = null;
switch (type) {
case 'Input':
Component = <InputElem item={item} key={name}/>
break;
case 'Select':
Component = <SelectElem item={item} key={name} />
break;
case 'DatePicker':
Component = <DatePickerElem item={item} key={name} />
break
default:
break;
}
return Component;
})
// 重置
const onReset = () => {
form.resetFields();
};
//提交
const onSubmit = (fieldsValue) => {
const values = {
...fieldsValue,
'createTime': fieldsValue['createTime'].format('YYYY-MM-DD HH:mm:ss'),
}
console.log(values);
}
return (
<Form form={form} onFinish={onSubmit} >
{formItems}
<Form.Item>
<Button type="primary" htmlType="submit">
提交
</Button>
</Form.Item>
<Button htmlType="button" onClick={onReset}>
重置
</Button>
</Form>
)
}
export default FormCom
3、InputElem.js
import React from 'react'
import {Input, Form} from 'antd'
const InputElem = (props => {
const { item } = props;
const { label, name, rules } = item;
return (
<Form.Item name={name} label={label} rules={rules}>
<Input />
</Form.Item>
)
})
export default InputElem
4、SelectElem.js
import React from 'react'
import { Select, Form } from 'antd'
const { Option } = Select;
const SelectElem = (props) => {
console.log(props);
const { item: { name, label, rules, options } } = props;
const optionItems = options.map(option => {
const { label, value } = option;
return <Option value={value} key={label}>{label}</Option>
})
return (
<Form.Item name={name} label={label} rules={rules}>
<Select>
{optionItems}
</Select>
</Form.Item>
)
}
export default SelectElem
5、DatePickerElem.js
import React from 'react'
import { Form, DatePicker } from 'antd';
const DatePickerElem = (props) => {
const { label, name, rules } = props.item;
return (
<Form.Item label={label} name={name} rules={rules}>
<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
</Form.Item>
)
}
export default DatePickerElem
6、结果展示
?
|