简体   繁体   English

如何使用 react-hotkeys-hook 提交带有 react-hook-form 的表单

[英]How to use react-hotkeys-hook to submit a form with react-hook-form

I want to submit a form with react-hook-form using the useHotKeys from react-hotkeys-hook我想使用 react-hotkeys-hook 中的 useHotKeys 提交带有 react-hook-form 的表单

I have attached a code sandbox trying this.我已经附加了一个代码沙箱来尝试这个。 I want to submit a form when a hotkey is clicked as well as when the submit button is clicked.我想在单击热键以及单击提交按钮时提交表单。 Can this be done?这可以做到吗?

https://codesandbox.io/s/react-hoot-form-usehotkeys-009rk?file=/src/App.js https://codesandbox.io/s/react-hoot-form-usehotkeys-009rk?file=/src/App.js

It can be done using the handleSubmit method for react-hook-forms.可以使用 react-hook-forms 的 handleSubmit 方法来完成。 The mistake that is made is that handleSubmit is a callback, hence it needs to be called like this.犯的错误是handleSubmit是一个回调,因此需要像这样调用它。

handleSubmit(onSubmit)()

and not like this handleSubmit(onSubmit)并且不喜欢这个handleSubmit(onSubmit)

My form uses material-ui-confirm to conditionally confirm submissions, but when I added the option to submit it by using hotkeys, using handleSubmit(onSubmit)() , that confirmation would be ignored.我的表单使用material-ui-confirm有条件地确认提交,但是当我添加使用热键提交它的选项时,使用handleSubmit(onSubmit)() ,该确认将被忽略。

I did this workaround and it seems to be working, though:我做了这个解决方法,但它似乎有效:


  // 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

Maybe the same logic can be applied to validation, since this way you have access to the data object before handleSubmit is fired?也许相同的逻辑可以应用于验证,因为这样您可以在触发 handleSubmit 之前访问data handleSubmit

A but convoluted, but that's all I got for now.一个但令人费解的,但这就是我现在所得到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM