gpt4 book ai didi

javascript - 如何在 React Hook 表单中将对象传递给 onSubmit

转载 作者:行者123 更新时间:2023-12-04 16:24:48 25 4
gpt4 key购买 nike

使用 react-hook-form 时我需要将任意数据传递到 onSubmit功能。示例代码:

function App() {
const { register, handleSubmit } = useForm();
const navigation = { foo: 'bar' }; // object to pass
const onSubmit = (data) => {
// how to access navigation here?
console.log(data);
console.log(navigation); // undefined
};
return (
<form onSubmit={handleSubmit(onSubmit)}> // <<== pass navigation here as arg?
<input defaultValue="test" {...register("example")} />
<input type="submit" />
</form>
);
}
我怎样才能传递我的对象 navigation进入 onSubmit ?

最佳答案

handleSubmit(onSubmit)表示您正在通过 onSubmit通过引用,它采用 data默认情况下,调用handleSubmit像这样 :

<form onSubmit={handleSubmit(data => onSubmit(data, navigation))}>
并且该对象应在此处可用:
const onSubmit = (data, obj) => {
console.log(data, obj);
};

关于javascript - 如何在 React Hook 表单中将对象传递给 onSubmit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66993491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com