reactjs 自定义Input组件上的React Hook Form错误

mu0hgdu0  于 2023-06-05  发布在  React
关注(0)|答案(1)|浏览(155)

当我在我的应用程序中使用react hook form + zod时,我遇到了一个问题,简而言之,输入永远不会改变值,我在控制台中得到以下错误:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

我的组件:

// Login.tsx

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

import { Button } from "../components/Form/Button";
import { Input } from "../components/Form/Input";

const loginFormValidationSchema = z.object({
  username: z.string().min(3),
  password: z.string().min(3)
});

type LoginFormFields = z.infer<typeof loginFormValidationSchema>;

export function Login() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting }
  } = useForm<LoginFormFields>({
    resolver: zodResolver(loginFormValidationSchema)
  });

  function handleSignIn(data: LoginFormFields) {
    console.log(data);
  }

  return (
    <section>
      <h1>Login</h1>

      <form onSubmit={handleSubmit(handleSignIn)}>
        <Input
          type="text"
          error={errors.username?.message}
          autoComplete="off"
          {...register("username")}
        />

        <Input
          type="password"
          label="Senha"
          error={errors.password?.message}
          {...register("password")}
        />

        <Button type="submit" disabled={isSubmitting}>
          Entrar
        </Button>
      </form>
    </section>
  );
}
// Input.tsx

import { InputHTMLAttributes } from "react";

import styles from "./Input.module.css";

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
  name: string;
  label?: string;
  error?: string;
}

export function Input({ name, label, error, ...props }: InputProps) {
  return (
    <div className={styles.wrapper}>
      {!!label && (
        <label htmlFor={name} className={styles.label}>
          {label}
        </label>
      )}

      <input id={name} name={name} className={styles.input} {...props} />

      {!!error && <p className={styles.error}>{error}</p>}
    </div>
  );
}

我已经尝试了一些替代方案,我发现在一些线程,但到目前为止,我还没有成功,有没有人经历过至少或有任何概念,它是如何可能绕过这个错误?

tnkciper

tnkciper1#

我认为发生的事情是{...register("username")},在Input组件的props中作为...props被拾取,在后台使用了ref(这是react-hook-form库识别输入的方式)。您应该能够通过将Input组件转换为使用forwardRef来修复此问题,如下所示:

export const Input = React.forwardRef<HTMLInputElement, Omit<InputProps, "ref">>(({ name, label, error, ...props }, ref) => (
    <div className={styles.wrapper}>
      {!!label && (
        <label htmlFor={name} className={styles.label}>
          {label}
        </label>
      )}

      <input id={name} name={name} className={styles.input} ref={ref} {...props} />

      {!!error && <p className={styles.error}>{error}</p>}
    </div>
));

Input.displayName = "Input";

基本上,它允许您在Input组件上放置ref属性,该属性将“转发”到input组件。这允许库监视更改。

相关问题