如何向 `handleSubmit` 注入自定义属性/方法?

huangapple go评论142阅读模式
英文:

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

问题

我使用 react hook form,并且我正在寻找一种方法来向该 hook 返回的 handleSubmit 方法注入自定义属性。我需要这样做的原因是,我的组件充当 state libraryConsumer,并且我想要在提交表单后更新状态。我可能还想向该方法传递属性。

从查看 API 来看,似乎不可能实现这一点。对于解决方法或如何实现此功能,您有什么想法吗?

英文:

I'm using 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, and I want to update the state after submitting the form. I may also want to pass props to the method.

From looking at the API, it seems like this isn't possible. Any thoughts on a workaround or how to do this?

答案1

得分: 2

I don't use this library, but it seems that getValues function returned from useForm hook opens the way to synchronize Your component state with form data stored in the "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>
  );
}
英文:

I don't use this library, but it seems that getValues function returned from useForm hook opens the way to synchronize Your component state with form data stored in the "react-hook-form":

docs

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

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

  const values = useMemo(() =&gt; getValues());

  useEffect(() =&gt; setValuesState(values), [values]);

  return (
    &lt;form&gt;
      [...]
    &lt;/form&gt;
  );
}

答案2

得分: 1

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

export default function App() {
  const { register, getValues } = useForm();
  const onSubmit = data => {
    // 在此处进行状态更新 update(data)
  }

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

why not just update the state during handleSubmit?

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

  return (
    &lt;form onSubmit={handleSubmit(onSubmit)}&gt;
      [...]
    &lt;/form&gt;
  );
}

huangapple
  • 本文由 发表于 2020年1月6日 23:35:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定