如何使用 react-hotkeys-hook 提交带有 react-hook-form 的表单
How to use react-hotkeys-hook to submit a form with react-hook-form
我想使用 react-hotkeys-hook 中的 useHotKeys 提交带有 react-hook-form 的表单
我附上了一个代码沙箱来尝试这个。我想在单击热键以及单击提交按钮时提交表单。这能做到吗?
https://codesandbox.io/s/react-hoot-form-usehotkeys-009rk?file=/src/App.js
可以使用 react-hook-forms 的 handleSubmit 方法来完成。犯的错误是 handleSubmit 是一个回调,因此需要这样调用。
handleSubmit(onSubmit)()
不是这样的handleSubmit(onSubmit)
我的表单使用 material-ui-confirm
有条件地确认提交,但是当我添加使用热键提交的选项时,使用 handleSubmit(onSubmit)()
,该确认将被忽略。
我做了这个解决方法,但它似乎有效:
// had to extract confirmation logic to a function
const confirmSub = async (data: any) => {
if (!conditions) {
await confirm({
title: "Message",
description: "Desc",
});
}
};
// fire submission when the user presses ctrl+enter on a textarea
// notice how onSubmit() is called
useHotkeys(
"ctrl+enter",
() => {
handleSubmit(async (data) => {
await confirmSub(data);
await onSubmit(data);
})();
},
{
enableOnTags: ["TEXTAREA"],
},
);
const onSubmit = async (data: any) => {
// have to keep this in case the user uses a button to submit
await confirmSub(data);
await mutation.mutate(data);
};
// define mutations and rest of the code below
也许可以将相同的逻辑应用于验证,因为这样您就可以在触发 handleSubmit
之前访问 data
对象?
一个但是很复杂,但我现在就知道这些了。
我想使用 react-hotkeys-hook 中的 useHotKeys 提交带有 react-hook-form 的表单
我附上了一个代码沙箱来尝试这个。我想在单击热键以及单击提交按钮时提交表单。这能做到吗?
https://codesandbox.io/s/react-hoot-form-usehotkeys-009rk?file=/src/App.js
可以使用 react-hook-forms 的 handleSubmit 方法来完成。犯的错误是 handleSubmit 是一个回调,因此需要这样调用。
handleSubmit(onSubmit)()
不是这样的handleSubmit(onSubmit)
我的表单使用 material-ui-confirm
有条件地确认提交,但是当我添加使用热键提交的选项时,使用 handleSubmit(onSubmit)()
,该确认将被忽略。
我做了这个解决方法,但它似乎有效:
// had to extract confirmation logic to a function
const confirmSub = async (data: any) => {
if (!conditions) {
await confirm({
title: "Message",
description: "Desc",
});
}
};
// fire submission when the user presses ctrl+enter on a textarea
// notice how onSubmit() is called
useHotkeys(
"ctrl+enter",
() => {
handleSubmit(async (data) => {
await confirmSub(data);
await onSubmit(data);
})();
},
{
enableOnTags: ["TEXTAREA"],
},
);
const onSubmit = async (data: any) => {
// have to keep this in case the user uses a button to submit
await confirmSub(data);
await mutation.mutate(data);
};
// define mutations and rest of the code below
也许可以将相同的逻辑应用于验证,因为这样您就可以在触发 handleSubmit
之前访问 data
对象?
一个但是很复杂,但我现在就知道这些了。