Hooks封装常见弹窗Form [react、antd、hooks]

1,103 阅读1分钟

对常见的编辑添加逻辑同时存在的弹窗表单的业务封装

hooks

/** 添加和编辑表格常见逻辑封装 */
const useModalForm = (
  /** 主键的名字 */
  primaryKeyName?: string,
) => {
  const [form] = useForm();
  // const formRef: ModalFormProps['formRef'] = useRef();
  const [visible, setVisible] = useState(false);
  const isEditRef = useRef(false);
  const editTargetRef = useRef(null);
  useEffect(() => {
    if (!visible) isEditRef.current = false;
  }, [visible]);

  const triggeEdit = (fieldsValue?: Record<string, any>) => {
    if (fieldsValue) {
      form?.setFieldsValue(fieldsValue);
      // 默认取fieldsValue的id作为主键,primaryKeyName
      editTargetRef.current = fieldsValue[primaryKeyName ?? 'id'];
    }
    isEditRef.current = true;
    setVisible(true);
  };
  const onVisibleChange = (v: boolean) => {
    if (v && !isEditRef.current) {
      // 添加的时候,重置值
      form.resetFields();
    }
    setVisible(v);
  };

  return {
    formProps: {
      form,
      onVisibleChange,
      visible,
    },
    /**
     * 触发编辑操作
     * @params fieldsValue旧值
     */
    triggeEdit,
    isEdit: isEditRef.current,
    /** 目标id */
    target: editTargetRef.current,
  };
};

使用

import { useModalForm } from '@/components/Form';
import { DrawerForm } from '@/components/Form';
import { ProFormSelect, ProFormText } from '@/components/Form';
import { Button } from 'antd';
import React from 'react';

/** useModalForm的demo */
const PageOrganizationList: React.FC = () => {
  /** 很帅的form? */
  const coolcoolForm = useModalForm();
  const coolForm = (
    <DrawerForm
      {...coolcoolForm.formProps}
      trigger={<Button>添加</Button>}
      onFinish={async (formData) => {
        if (coolcoolForm.isEdit) {
          console.log(`编辑id为:${coolcoolForm.target}`, formData);
          return true;
        }
        console.log('添加', formData);
        return true;
      }}
    >
      <ProFormText name="1" label="机构名称" />
      <ProFormText name="2" label="原商务" />
      <ProFormSelect
        name="3"
        label="选择账号"
        options={[
          { label: '分类1', value: '1' },
          { label: '分类2', value: '2' },
          { label: '分类3', value: '3' },
        ]}
      />
    </DrawerForm>
  );

  return (
    <>
      <a onClick={() => coolcoolForm.triggeEdit({ 1: '1', 2: '2', 3: '3', id: 10086 })}>编辑</a>
      {coolForm}
    </>
  );
};
export default PageOrganizationList;

效果