如何使用 React-Hook-Form 设置 ref 焦点

Twi*_*man 7 reactjs react-hook-form

您如何使用 React-Hook-Form 在输入中实现设置焦点,这是他们的常见问题解答中的“如何共享引用使用”代码https://www.react-hook-form.com/faqs/#Howtosharerefusage

import React, { useRef } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit } = useForm();
  const firstNameRef = useRef();
  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={(e) => {
        register(e)
        firstNameRef.current = e // you can still assign to ref
      }} />
      <input name="lastName" ref={(e) => {
        // register's first argument is ref, and second is validation rules
        register(e, { required: true })
      }} />

      <button>Submit</button>
    </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

我尝试在 useEffect 中设置 ref 的焦点,但它不起作用:

useEffect(()=>{
   firstNameRef.current.focus();
},[])
Run Code Online (Sandbox Code Playgroud)

输入内部也没有:

<input name="firstName" ref={(e) => {
    register(e)
    firstNameRef.current = e;
    e.focus();
}} />
Run Code Online (Sandbox Code Playgroud)

Bry*_*yce 17

您可以使用 useForm 挂钩返回的帮助器设置焦点setFocus(无需使用自定义引用):

 const allMethods = useForm();
 const { setFocus } = allMethods;

 ...

 setFocus('inputName');
Run Code Online (Sandbox Code Playgroud)

https://react-hook-form.com/api/useform/setFocus

  • 新链接:https://www.react-hook-form.com/api/useform/setfocus (3认同)

Mag*_*med 6

如果您使用版本 7,您可以查看文档中的此链接

https://www.react-hook-form.com/faqs/#Howtosharerefusage


Ste*_*e S 5

你在使用打字稿吗?

如果是这样,请更换...

const firstNameRef = useRef();

和...

const firstNameRef = useRef<HTMLInputElement | null>(null);