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

Eba*_*dta 9 reactjs material-ui react-hook-form

我在使用react-hook-form 和material-ui 时遇到了困难。

我准备了一个codesandbox示例

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

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

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

Nea*_*arl 16

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

<input {...register('name')} />
Run Code Online (Sandbox Code Playgroud)

调用register()将为您的输入返回必要的属性,例如onChangeonBlurrefreact-hook-form这些道具使跟踪您的表单数据成为可能。现在,当您像这样使用registerMaterial-UI时:TextField

<TextField {...register('name')} />
Run Code Online (Sandbox Code Playgroud)

您可以将ref属性直接传递到 ,TextField而放置它的正确位置是inputRef

<TextField inputRef={ref} />
Run Code Online (Sandbox Code Playgroud)

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

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

如何正确使用注册功能来获取错误消息

您的错误处理代码没有任何问题。尽管您可以使用 Typescript 的可选链接运算符 来进一步缩短代码?.

<TextField
  error={!!errors.vasarlo}
  helperText={errors?.vasarlo?.message}
  inputRef={ref}
  {...inputProps}
/>
Run Code Online (Sandbox Code Playgroud)

现场演示

编辑 67009085/latest-react-hook-form-error-handling-with-material-ui-textfield