英文:
Way to inject custom props/methods to `handleSubmit`?
问题
我使用 react hook form,并且我正在寻找一种方法来向该 hook 返回的 handleSubmit
方法注入自定义属性。我需要这样做的原因是,我的组件充当 state library 的 Consumer
,并且我想要在提交表单后更新状态。我可能还想向该方法传递属性。
从查看 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":
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":
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>
);
}
答案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 => {
// do your state update here update(data)
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
[...]
</form>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论