reactjs 如何以编程方式提交react-hook-form?

46qrfjad  于 2023-05-17  发布在  React
关注(0)|答案(2)|浏览(179)

我正在尝试将react-hook-form添加到我的react.js项目中。形式定义为:

<form onSubmit={handleSubmit(onSubmit)} ref={submitRef}>
          //some input elements
          <div className='d-flex justify-content-center' >
            <button
              type="submit"
              className=" btn btn-warning" >
              submit            
            </button>
          </div>
</form>

onSubmit方法定义为:

const onSubmit = data => {
    console.log(data)
  };

我尝试定义一个计时器(比如10分钟),并且希望在计时器过期时触发表单的onSubmit事件。为此,我使用了react-timer-hook,如下所示:

const time = new Date();
  time.setSeconds(time.getSeconds() + 2);

  let submitRef = useRef()

  const {
    seconds,
    minutes,
    hours,
    days,
    isRunning,
    start,
    pause,
    resume,
    restart,
  } = useTimer({ time, onExpire: () => want to trigger the form submit event });

如何定义onExpire属性?

kse8i1jr

kse8i1jr1#

formRef.current.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }))
kupeojn6

kupeojn62#

您可以手动调用handleSubmit
docs

// It can be invoked remotely as well
handleSubmit(onSubmit)();

// You can pass an async function for asynchronous validation.
handleSubmit(async (data) => await fetchAPI(data))

类似的东西(未经测试)

import { useEffect } from 'react';
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  useEffect(() => {
    handleSubmit(onSubmit)();
  }, [])

  return (
    /* "handleSubmit" will validate your inputs before invoking "onSubmit" */
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* register your input into the hook by invoking the "register" function */}
      <input defaultValue="test" {...register("example")} />
      
      {/* include validation with required or other standard HTML validation rules */}
      <input {...register("exampleRequired", { required: true })} />
      {/* errors will return when field validation fails  */}
      {errors.exampleRequired && <span>This field is required</span>}
      
      <input type="submit" />
    </form>
  );
}

相关问题