react、vue动态form表单

需求在日常开发中反复写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

原创不易,请关注谢谢支持

相关推荐
飞天大河豚2 分钟前
2025前端框架最新组件解析与实战技巧:Vue与React的革新之路
vue.js·react.js·前端框架
MickeyCV13 分钟前
Nginx学习笔记:常用命令&端口占用报错解决&Nginx核心配置文件解读
前端·nginx
祈澈菇凉30 分钟前
webpack和grunt以及gulp有什么不同?
前端·webpack·gulp
十步杀一人_千里不留行33 分钟前
React Native 下拉选择组件首次点击失效问题的深入分析与解决
javascript·react native·react.js
zy01010137 分钟前
HTML列表,表格和表单
前端·html
初辰ge40 分钟前
【p-camera-h5】 一款开箱即用的H5相机插件,支持拍照、录像、动态水印与样式高度定制化。
前端·相机
HugeYLH1 小时前
解决npm问题:错误的代理设置
前端·npm·node.js
六个点1 小时前
DNS与获取页面白屏时间
前端·面试·dns
customer082 小时前
【开源免费】基于SpringBoot+Vue.JS医疗报销系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
道不尽世间的沧桑2 小时前
第9篇:插槽(Slots)的使用
前端·javascript·vue.js