在 React Hook Forms 7 中共享引用使用两次

Tho*_*Byy 4 javascript reactjs

我希望我已经接近将旧的 React hook 表单转换为 RHF7,但我一直试图用 2 个不同的输入来共享 refs 两次。有人可以帮我完成这段代码吗...所以我需要在 dobMonth 和 dobYear 上都有一个引用,但我不能使用同一个引用两次,所以我需要创建第二个引用,但它不允许我这样做。

  const dobMonthInput = useRef(null)
  const dobYearInput = useRef(null)

  const {
    register
  } = useForm()

  const { ref, ...rest } = register('dobMonth', {
    required: true,
    validate: (value) => validateDate(value, getValues),
    onChange: (e) => onChange(e),
  })
  /*const { ref, ...rest } = register('dobYear', {
    required: true,
    validate: (value) => validateDate(value, getValues),
    onChange: (e) => onChange(e),
  })*/


  ....



  <input
        name="dobDay"
        type="text"
        {...register('dobDay', {
            required: true,
            validate: (value) => validateDate(value, getValues),
            onChange: (e) => onChange(e),
        })}
  />

  <input
        name="dobMonth"
        type="text"
        {...rest}
        ref={(e) => {
            ref(e)
            dobMonthInput.current = e
        }}
  />
  <input
        name="dobYear"
        type="text"
        {...rest}
        ref={(e) => {
            ref(e)
            dobYearInput.current = e
        }}
  />
Run Code Online (Sandbox Code Playgroud)

我最终需要使用dobMonthInput.current.focus()dobYearInput.current.focus()

我收到错误Identifier 'ref' has already been declared的原因很明显,但我不知道如何解决它。谢谢

Ane*_*iad 6

您在反应钩子引用之间存在引用声明问题,该引用已分配给同一输入,您需要创建引用,但不使用已分配给另一个输入的引用。

这里解决问题的技巧:

  const dopMReg = register("dobMonth");
  const dopYReg = register("dobYear");
Run Code Online (Sandbox Code Playgroud)

例如:

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

export default function App() {
  const { register, handleSubmit } = useForm();
  const dobMonthInput = useRef(null);
  const dobYearInput = useRef(null);
  const onSubmit = (data) => {
    console.log(data);
    dobMonthInput.current.focus();
  }
  const dopMReg = register("dobMonth");
  const dopYReg = register("dobYear");

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        name="dobMonth"
        type="text"
        {...dopMReg}
        ref={(e) => {
          dopMReg.ref(e);
          dobMonthInput.current = e;
        }}
      />
      <input
        name="dobYear"
        type="text"
        {...dopYReg}
        ref={(e) => {
          dopYReg.ref(e);
          dobYearInput.current = e;
        }}
      />
      <button>Submit</button>
    </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

这是演示网址

  • 惊人的帮助,谢谢!被困在这个问题上几个小时 (2认同)