需求在日常开发中反复写form 是一种低效的开发效率,布局而且还不同这就需要我们对其封装
为了简单明了看懂代码,我这里没有组件,都放在一起,简单抽离相信作为大佬的你,可以自己完成,
一、首先我们做动态form 要明白几点:
1、类型,2、检验,3、不同组件又不同的方法事件(重点)4、布局(更加通用型)
UI库是antd(element同理替换组件即可主要是父组件formItems标签替换)
TypeScript
import {Button, Cascader, Col, DatePicker, Form, Input, InputNumber, Mentions, Row, Select, TreeSelect} from "antd";
import React from "react";
import style from "./style.less";
const {RangePicker} = DatePicker;
const formItemLayout = {
labelCol: {
xs: {span: 24},
sm: {span: 6},
},
wrapperCol: {
xs: {span: 24},
sm: {span: 18},
},
};
type ColSpanType = {
offset?: number;
xs?: number;
sm?: number;
md?: number;
lg?: number;
xl?: number;
};
const FormApp: React.FC = () => {
//根据ui 设置布局
const responsiveLayout: ColSpanType = {
xs: 24,
sm: 24,
md: 8,
lg: 8,
xl: 8,
};
const formItems = [
{
label: 'Input',
name: 'Input',
rules: [{required: true, message: "Please input!"}],
component: Input,
placeholder: '请输入',
events: {
onChange: (e) => console.log(e.target.value),
onFocus: () => console.log('Input focused'),
// Add other events here
},
},
// ... other form items ...
];
return (
<Form {...formItemLayout} className={style.formContainer}>
{formItems.map((item, index) => (
<Col {...responsiveLayout} key={index}>
<Form.Item label={item.label} name={item.name} rules={item.rules}>
<item.component placeholder={item.placeholder} style={{width: "100%"}} {...item.events} />
</Form.Item>
</Col>
))}
<Col span={24}>
<Row justify='end'>
<Form.Item>
<Button type='primary' htmlType='submit'>
Submit
</Button>
</Form.Item>
</Row>
</Col>
</Form>
);
};
export default FormApp;
二、完整组件分离代码
由于代码太多见gitee
父组件 src/pages/form/index.tsx · Jim/react-new-umi-antd-2024 - Gitee.com
表单组件 DynamicForms src/components/DynamicForms/index.tsx · Jim/react-new-umi-antd-2024 - Gitee.com
如果是vue 同学 DynamicForms直接拷贝使用(组件还是tsx/jsx 不要放在.vue 文档中组件还是不要用.vue 局限性太大),只需要把父组件的Dom 结构改的。推荐vu3 setup
原创不易,请关注谢谢支持