将自定义 props/methods 注入 `handleSubmit` 的方法?

Way to inject custom props/methods to `handleSubmit`?

我正在使用 react hook form, and I'm looking for a way to inject custom props to the handleSubmit method returned by the hook. The reason I need to do this is my component acts as a Consumer for a state library,我想在提交表单后更新状态。我可能还想将道具传递给方法。

从 API 来看,这似乎是不可能的。关于解决方法或如何执行此操作的任何想法?

我不使用这个库,但是从 useForm 钩子返回的 getValues 函数似乎开启了将您的组件状态与存储在 "react-hook-form" 中的表单数据同步的方法:

docs

import React, { useMemo, useEffect, useState } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, getValues } = useForm();
  const [ valuesState, setValuesState ] = useState();

  const values = useMemo(() => getValues());

  useEffect(() => setValuesState(values), [values]);

  return (
    <form>
      [...]
    </form>
  );
}

为什么不在 handleSubmit 期间更新状态?

export default function App() {
  const { register, getValues } = useForm();
  const onSubmit = data => {
    // do your state update here update(data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      [...]
    </form>
  );
}