Ant —— Hooks Drawer Form组件探索

Antd开发中需要弹窗的Form表单完成增改,提交表单,繁琐写很多重复代码,必要去写一个自定义组件

image.png

code:

import React, {
  useState,
  useImperativeHandle,
  forwardRef,
  useCallback,
  memo,
  useMemo
} from "react";
import { Space, Button, Form, Drawer, Input } from "antd";

const CustomDrawer = (props, ref) => {
  const { onOk } = props;

  const [visible, setVisible] = useState(false);
  const [source, setSource] = useState(null);
  const [pedding, setPedding] = useState(false);

  const [form] = Form.useForm();

  const title = useMemo(() => {
    return source ? "编辑" : "新增";
  }, [source]);

  useImperativeHandle(ref, () => ({
    show(_) {
      setVisible(true);
      if (_) {
        //修改编辑部分
        setSource(_);
        /** code to do ... */
        form.setFieldsValue(_);
      }
    }
  }));

  const handleClose = useCallback(() => {
    setVisible(false);
    setSource(null);
    form.resetFields();
    /* 自定义 code to do ... */
  }, []);

  const handleOk = () => {
    if (pedding) return;
    setPedding(true);
    form
      .validateFields()
      .then(async (values) => {
        /* some code ... */
        console.log(values);
        onOk();
        handleClose();
      })
      .catch((err) => {});
    setPedding(false);
  };

  return (
    <Drawer
      footer={
        <div style={{ textAlign: "right" }}>
          <Space>
            <Button onClick={handleClose}>取消</Button>
            <Button type="primary" onClick={handleOk}>
              确定
            </Button>
          </Space>
        </div>
      }
      visible={visible}
      destroyOnClose={true}
      // width={ }  /*自定义*/
      title={title}
      onClose={handleClose}
    >
      <Form layout="vertical" form={form} hideRequiredMark scrollToFirstError>
        <Form.Item>
          <Input autoComplete="off" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default memo(forwardRef(CustomDrawer));

使用:

import "./styles.css";
import CustomDrawer from "./CustomDrawer";
import "antd/dist/antd.css";
import { useRef } from "react";
import { Button, Space } from "antd";

export default function App() {
  const drawer = useRef();
  return (
    <div className="App">
      <Space>
        <Button type="primary" onClick={() => drawer.current.show()}>
          添加
        </Button>
        <Button onClick={() => drawer.current.show("edit")}>编辑</Button>
      </Space>
      <CustomDrawer ref={drawer} />
    </div>
  );
}

闲来无事写个组件玩儿。。。

推荐阅读更多精彩内容