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 (
    
          
            
            
          
        
} visible={visible} destroyOnClose={true} // width={ } /*自定义*/ title={title} onClose={handleClose} >
); }; 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 (
    
); }

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

你可能感兴趣的:(Ant —— Hooks Drawer Form组件探索)