reactjs 如何将react-hook-formref与自定义输入组件连接

6tdlim6h  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(97)

我对使用react-hook-form进行数据验证很感兴趣,我有一个定制的TextField组件,如下所示。

    • 一米一米一**
function Label({ id, children }) {
  return (
    <label
      htmlFor={id}
      className="block mb-3 text-sm font-medium text-gray-700"
    >
      {children}
    </label>
  );
}

export function TextField({
  id,
  label,
  inputRef,
  type = "text",
  className = "",
  ...props
}) {
  return (
    <div className={className}>
      {label && <Label id={id}>{label}</Label>}
      <input id={id} ref={inputRef} type={type} {...props} />
    </div>
  );
}

我试过像这样使用react-hook-form

    • 一米三米一x**
import { TextField } from "./components/Fields";
import { useForm } from "react-hook-form";
import { useEffect } from "react";

export default function App() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm();
  const mytest = register("mytest", { required: "mytest is a required field" });

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

  useEffect(() => console.log(errors), [errors])

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <TextField
        id="mytest"
        name={mytest.name}
        inputRef={mytest.ref}
        label="This is a test"
        placeholder="Placeholder"
      />
      <input type="submit" />

    </form>
  );
}

但它不能正常工作。

我也尝试过使用forwardRef,但没有效果。

v1l68za4

v1l68za41#

在正确应用forwardRef后,终于可以工作了。仍然很好奇是否有更好的方法,所以我将这个问题留到一边。

    • 一米一米一**
import { forwardRef } from "react";

function Label({ id, children }) {
  return (
    <label
      htmlFor={id}
      className="block mb-3 text-sm font-medium text-gray-700"
    >
      {children}
    </label>
  );
}

export const TextField = forwardRef(function TextField({
  id,
  label,
  type = "text",
  className = "",
  ...props
}, ref) {
  return (
    <div className={className}>
      {label && <Label id={id}>{label}</Label>}
      <input id={id} ref={ref} type={type} {...props} />
    </div>
  );
});
    • 一米二米一x**
import { TextField } from "./components/Fields";
import { useForm } from "react-hook-form";
import { useEffect } from "react";

export default function App() {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm();
  
  const mytest = register("mytest", { required: "mytest is a required field" });

  const onSubmit = (data) => console.log("data", data);

  useEffect(() => console.log(errors), [errors])

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <TextField
        id="mytest"
        label="This is a test"
        placeholder="Placeholder"
        {...mytest}
      />
      {errors.mytest && <>{errors.mytest.message}</>}
      <input type="submit" />

    </form>
  );
}

相关问题