使用 material-ui TextField 的最新 react-hook-form 错误处理

latest react-hook-form error handling with material-ui TextField

我有困难,使用 react-hook-form 和 material-ui。

我准备了一个codesandbox example.

import { TextField } from "@material-ui/core";
import React from "react";
import { useForm } from "react-hook-form";
import "./styles.css";

interface IMyForm {
  vasarlo: string;
}

export default function App() {
  const {
    handleSubmit,
    formState: { errors },
    register
  } = useForm<IMyForm>();

  const onSubmit = (data: IMyForm) => {
    alert(JSON.stringify(data));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>First Name</label>
      <TextField
        variant="outlined"
        margin="none"
        label="Test"
        {...register("vasarlo", {
          required: "error text"
        })}
        error={errors?.vasarlo ? true : false}
        helperText={errors?.vasarlo ? errors.vasarlo.message : null}
      />
      <input type="submit" />
    </form>
  );
}

如何正确使用注册功能,获取错误消息,写入输入字段,以及 onSubmit 功能正常工作?

我在该场景的文档中找不到答案。

您在滥用 Controller。 react-hook-form 的默认功能是使用不受控制的输入。删除 <Controller/> 并将其放在您的 TextField

inputRef={register({
    required: 'This is required',
    validate: (data) => myValidationFunction(data)
})}

如果您需要 modify/intercept/format TextField 中显示的值与用户键入的值不同,即 phone 数字,则您只需要使用控制器仅输入数字时显示为 (xxx)-xxx-xxxx。

react-hook-form v7 中,这是注册输入的方式:

<input {...register('name')} />

调用 register() 将为您的输入 return 必要的道具,例如 onChangeonBlurref。这些道具使 react-hook-form 可以跟踪您的表单数据。现在,当您像这样将 register 与 Material-UI TextField 一起使用时:

<TextField {...register('name')} />

您将 ref 属性 直接传递给 TextField 而正确的放置位置是 inputRef:

<TextField inputRef={ref} />

所以你必须像这样修改你的代码:

const { ref: inputRef, ...inputProps } = register("vasarlo", {
  required: "error text"
});
<TextField inputRef={inputRef} {...inputProps} />

How can I properly use the register function, to get error message

您的错误处理代码没有任何问题。尽管您可以使用 Typescript 的 optional chaining operator ?.:

来缩短代码
<TextField
  error={!!errors.vasarlo}
  helperText={errors?.vasarlo?.message}
  inputRef={ref}
  {...inputProps}
/>

现场演示