React 动态表单封装

import Component from "./Component";
import { Form, Button } from "antd";

const onFinish = (values) => {
  console.log("Success:", values);
};

const FormC = ({ data }) => {
  return (
    <Form onFinish={onFinish}>
      {data.map((item, index) => {
        let { label, name, rules, valuePropName, ...restProps } = item;

        return (
          <Form.Item
            label={label}
            name={name}
            rules={rules}
            valuePropName={valuePropName}
            key={index}
          >
            <Component {...restProps}></Component>
          </Form.Item>
        );
      })}

      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default FormC;

  

FormC 组件 ⬆️

 

const Component = ({ is, children, ...restProps }) => {
  const Tag = require("antd")[is];

  if (!Tag) return false;

  return <Tag {...restProps}>{children}</Tag>;
};

export default Component;

  

ComponentC ⬆️

 

使用

const data = [
  {
    is: "Input",
    label: "测试",
    name: "test",
  },
  {
    label: "案例",
    name: "done",
    valuePropName: "checked",
    is: "Switch",
    onClick: () => console.log(3333),
  },
];

  

<FormC data={data}></FormC>

  

posted @ 2020-11-27 12:11  winyh  阅读(364)  评论(0编辑  收藏  举报