Antd Form黑科技-监听表单值变化

useFormWatch

为啥要写这个hooks?主要是因为我们页面antd使用的是4.0版本,当时5.0还没有支持,而在一些业务场景中我需要监听某个表单值的变化来做一些回调处理,而Form组件的propsonValuesChange需要集中一个地方来写这些回调又不太方便于是便翻到了源码中RC_FORM_INTERNAL_HOOKS这个antd内置hooks事件,可以用来监听

import { FormInstance } from 'antd';
import { useEffect, useRef } from 'react';

export default function useFormWatch(
  fn: (v: { [x: string]: any }) => void,
  form?: FormInstance<any>,
  keyDeps: string[],
) {
  const preValue = useRef({});

  const preValueKey = Object.keys(preValue.current);

  // 删除不需要监控key
  preValueKey.forEach((key) => {
    if (!keyDeps.includes(key)) {
      delete preValue.current[key];
    }
  });
  // 新增监控key
  keyDeps.forEach((key) => {
    if (typeof key != 'string') {
      throw new Error('keyDeps must be string');
    }
    if (!preValueKey.includes(key)) {
      preValue.current[key] = undefined;
    }
  });

  useEffect(() => {
    if (!form) {
      return;
    }
    const formValue = form.getFieldsValue();

    Object.keys(preValue.current).forEach((key) => {
      preValue.current[key] = formValue[key];
    });
  }, [Object.keys(preValue.current).join(), form]);

  useEffect(() => {
    if (!form) {
      return;
    }
    /**
     * 表单初始化是异步的,在组件挂载时对应值可能还没有赋值
     * https://github1s.com/react-component/field-form/blob/HEAD/src/useForm.ts#L99-L100
     */
    //@ts-ignore
    const destroyWatch = form
      ?.getInternalHooks('RC_FORM_INTERNAL_HOOKS')
      ?.registerWatch((value: any) => {
        const obj = {};
        keyDeps.forEach((key) => {
          if (value[key] != preValue.current[key]) {
            obj[key] = value[key];
            preValue.current[key] = value[key];
          }
        });
        if (Object.keys(obj)?.length) {
          fn(obj);
        }
      });

    return destroyWatch;
  }, [preValue, fn, form]);
}

官方useWatch

antd在5.0版本支持类似的api: useWatch 可以替代

https://ant.design/components/form-cn#formusewatch

https://github1s.com/react-component/field-form/blob/master/src/useWatch.ts#L140

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

衣乌安、

嘿嘿,好心人赏俩钱儿~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值