简体   繁体   English

如何在 onChange 上提交反应表单字段,而不是使用 React-Hook-Form 库提交

[英]How to submit react form fields on onChange rather than on submit using React-Hook-Form library

I have started using new React-Hook-form library and wanted to submit my input fields on Change rather than on Submit.我已经开始使用新的 React-Hook-form 库,并且想在 Change 上而不是在 Submit 上提交我的输入字段。 Also, I am planning to use debounce from Lodash to avoid re-rendering另外,我打算使用 Lodash 的 debounce 来避免重新渲染

This is what I have tried so far:这是我到目前为止所尝试的:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

export default function App() {
  const { register, handleSubmit, setValue } = useForm();
 

  useEffect(() => {
    register({ name: "firstName" }, { required: true });
  }, [register]);

  return (
    <form>
      <input
        name="firstName"
        onChange={(e) => {
          setValue("firstName", e.target.value);
          handleSubmit((data) => console.log("data", data));
        }}
      />
    </form>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

If you log your implementation of handleSubmit inside onChange , you will notice that it returns a function如果您在onChange中记录handleSubmit的实现,您会注意到它返回 function

在此处输入图像描述

Try to invoke the returned function and it should submit.尝试调用返回的 function 并且它应该提交。

onChange={(e) => {
    setValue("firstName", e.target.value);
    handleSubmit((data) => console.log("data", data))();
}}

I've also recently written my version of "user is done with typing, then submit" implementation for input fields - check it out: https://stackoverflow.com/a/63419790/8680805我最近还为输入字段编写了我的“用户完成输入,然后提交”实现的版本-检查一下: https://stackoverflow.com/a/63419790/8680805

I found the simplest way to be:我发现最简单的方法是:

const { handleSubmit, watch } = useForm();
const onSubmit = (data) => console.log(data)

useEffect(() => {
    const subscription = watch(handleSubmit(onSubmit));
    return () => subscription.unsubscribe();
}, [handleSubmit, watch]);

From your example it looks like you only want to retrieve (all) the values after input change.从您的示例看来,您只想在输入更改后检索(所有)值。 Not sure if this will help you, but you can use the getValues function from the useForm hook.不确定这是否对您有帮助,但您可以使用useForm挂钩中的getValues function。

const Filters: FC<TProps> = ({ filters, setActiveFilter }) => {
  const { register, getValues } = useForm();

  const handleChange = () => {
    const values = getValues();
    // Do something with values, in my case I have used the 'setActiveFilter' function above.
  };

  return (
    <form>
      {filters.map((filter) => (
        <fieldset key={filter.id}>
          <legend>{filter.label}</legend>
          {filter.options.map((option) => (
            <label htmlFor={option.value} key={option.id}>
              <input
                type="checkbox"
                id={option.value}
                name={filter.label}
                value={option.id}
                ref={register}
                onChange={handleChange}
              />
              {option.value}
            </label>
          ))}
        </fieldset>
      ))}
    </form>
  );
};

why do you want to submit it onChange?为什么要提交 onChange?

but if you really want to do it, this should work:但如果你真的想这样做,这应该工作:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import { useForm, useWatch } from "react-hook-form";

import "./styles.css";

export default function App() {
  const { register, control, handleSubmit } = useForm()
  const firstName = useWatch({ control, name: 'firstName' })

  useEffect(() => {
    if(firstName && firstName.length > 0) {
      handleSubmit(data => console.log("data", data))()
    }
  }, [firstName, handleSubmit])

  return (
    <form>
      <input ref={register({ required: true })} name="firstName" />
    </form>
  )
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

in react hook forms watch is the alternative way for onChange, simply do this:在反应钩子 forms 手表是 onChange 的替代方式,只需这样做:

const handleSubmit = (data) => {
 console.log(data)
}
    const {watch} = useForm();
    
          watch((data, { name }) => {
            if (name === "firstName") handleSubmit(data);
          });

Alex answer not working in my case since I need a small delay before submiting form (when user stopped typing)亚历克斯回答在我的情况下不起作用,因为我在提交表单之前需要一点延迟(当用户停止输入时)

Here is my solution这是我的解决方案

const { handleSubmit, watch } = useForm(); const { handleSubmit, watch } = useForm(); const onSubmit = (data) => console.log(data); const onSubmit = (data) => console.log(data);

useEffect(() => {
 const subscription = watch(() => {
   if (timer) clearTimeout(timer);

   timer = setTimeout(() => {
     handleSubmit(onSubmit)();
   }, 1000);
 });
 return () => subscription.unsubscribe();
}, [handleSubmit, watch]);

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

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