1. 程式人生 > 實用技巧 >React 動態表單封裝

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>