我正在try 为用户创建一个注册页面,并使用Reaction-Hook-Forms作为注册表单,使用Zod进行验证.当我测试表单时,一开始我可以输入任何内容,只有在提交后才会显示错误.然而,在此之后,错误不断地中断打字,例如,当我获得8个字符时,密码输入中断,当我输入数字时,再次中断.这种情况也发生在邮箱的输入中,其各自的消息错误也会发生.

我的REACTION-HOOK-FORMS设置为ON{MODE:"onSubmit"}.这是我下面的代码

import { useForm } from "react-hook-form";
import { z } from "zod";
import RegisterSchema from "../components/Authentication/Register/RegisterSchema";
import { AuthTitle } from "../components/Authentication";
import { zodResolver } from "@hookform/resolvers/zod";

type RegisterSchemaType = z.infer<typeof RegisterSchema>

type FormFieldProps = {
  labelText: string;
  inputText: string;
  registerInput: keyof RegisterSchemaType;
};

const Register = () => {

  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm<RegisterSchemaType>({ resolver: zodResolver(RegisterSchema), mode: "onSubmit"});

  const onSubmit = (data: RegisterSchemaType) => {
    console.log(data);
  }; 

  console.log(errors);

  const FormFields = ({ labelText, inputText, registerInput } : FormFieldProps) => (
    <div className='flex flex-col'>
      <label className='uppercase text-[#49A078] text-sm sm:text-md' htmlFor={inputText}>
        {labelText}
      </label>
      <div className="flex flex-col relative">
        <input
          {...register(registerInput)}
          className='mb-1 mt-1 p-3 outline-1 outline-[#263228] outline rounded-sm pr-5 focus:outline-[#49A078] focus:outline-2'
        />
        {errors[registerInput] && (
          <span className="text-red-500 text-sm mt-0 mb-4">{errors[registerInput]?.message}</span>
        )}
      </div>
    </div>
  );

  return (
    <div className="flex flex-col h-screen justify-center items-center">
      <AuthTitle title="Trace" subTitle="Register" />

      <div className="flex md:flex-row flex-col">
        <form className="flex flex-col p-5 pr-8 border-r border-gray-400" onSubmit={handleSubmit(onSubmit)}>
          <FormFields labelText="First Name" inputText="firstName" registerInput="firstName"/>
          <FormFields labelText="Surname" inputText="surname" registerInput="surname"/>
          <FormFields labelText="Email Address" inputText="email" registerInput="email"/>
          <FormFields labelText="Password" inputText="password" registerInput="password"/>
          <button className="bg-[#263228] text-white p-3 rounded-sm uppercase mt-3" type="submit">
            Register
          </button>
        </form>

        {/* OAuth buttons */}
        <div className="flex items-center justify-center p-4">
          {/* Google OAuth */}
          {/* You may need to replace this with the appropriate library */}
          <h1>LOREM IPSUM</h1>

          {/* Apple OAuth */}
          {/* Add Apple OAuth button here */}
        </div>
      </div>

      {/* Bottom link */}
      <div className="mt-auto">
        <p className="text-center text-[#49A078] uppercase">Already have an account?</p>
      </div>
    </div>
  );
};

export default Register;

这是我的注册表架构

import { z } from "zod";

const RegisterSchema = z.object({
  email: z.string().email({message: "Invalid email."}),
  firstName: z.string().min(2, {message: "Must be 2 or more characters long."}),
  surname: z.string().min(2, {message: "Must be 2 or more characters long."}),
  password: z.string()
    .min(8, {message: "Must be 8 or more characters long."})
    .refine((password) => /\d/.test(password), {message: 'Must contain at least 1 number.',})
});

export default RegisterSchema;

有没有办法让这些错误不中断输入字段的打字?我已经在线查看了react 挂钩表单,当它们出现错误时,输入字段仍然是可输入的.

我try 了使用Form方法的不同模式以及Reaction的State变量,但都不起作用.

推荐答案

我在我的项目中像这样使用它,从来没有遇到过这个问题.确保我只将值和On Change处理程序应用于输入

import { TextField as MuiTextField } from "@mui/material";
import React from "react";
import { useController as useFieldController } from "react-hook-form";

import { useFormControllerContext } from "@bujus/common-frontend";

const TextField = ({ isAutofocusing = false, isEnabled = true, label, name, type }) => {
    const formController = useFormControllerContext();

    const fieldController = useFieldController({
        control: formController.control,
        name,
    });

    return (
        <MuiTextField
            autoFocus={isAutofocusing}
            disabled={!isEnabled}
            error={fieldController.fieldState.error !== undefined}
            fullWidth
            {...(fieldController.fieldState.error === undefined
                ? {}
                : { helperText: fieldController.fieldState.error.message })}
            label={label}
            onChange={fieldController.field.onChange}
            {...(type === undefined ? {} : { type })}
            value={fieldController.field.value}
        />
    );
};

export { TextField };
import { useForm as useFormController } from "react-hook-form";

    const formController = useFormController({
        mode: "onChange",
        resolver: joiResolver(helperValidationSchemas.update.form, validationOptions),
        defaultValues: {
            username: helper.username,
        },
    });

Typescript相关问答推荐

如何使函数接受类型脚本中具有正确类型的链接修饰符数组

迁移到Reaction路由V6时,获取模块Reaction-Router-Dom';没有导出的成员RouteComponentProps错误

在实现自定义主题后,Angular 不会更新视图

为什么不能使用$EVENT接收字符串数组?

嵌套对象的类型

如何实现异构数组内函数的类型缩小

CDK从可选的Lambda角色属性承担角色/复合主体中没有非空断言

使用Redux Saga操作通道对操作进行排序不起作用

在打字脚本中对可迭代对象进行可变压缩

S,为什么我的T扩展未定义的条件在属性的上下文中不起作用?

如何使用泛型函数参数定义类型脚本函数

如何正确地将元组表格输入到对象数组实用函数(如ZIP)中,避免在TypeScrip 5.2.2中合并所有值

如何使函数参数数组不相交?

递归类型别名的Typescript 使用

我可以使用对象属性的名称作为对象中的字符串值吗?

如何使用 AWS CDK 扩展默认 ALB 控制器策略?

剧作家测试未加载本地网址

React HashRouter,单击导航栏时页面重新加载出现问题

为什么 typescript 在对象合并期间无法判断无效键?

如何让 Promise 将它调用的重载函数的类型转发给它自己的调用者?