将react-hook-form与typescript和material-ui一起使用来显示错误消息的正确方法

Mah*_*esh 6 typescript reactjs material-ui react-hook-form

我正在将react-hook-form与typescript和material-ui一起使用。我想将错误消息作为helperTextto传递TextField。我尝试使用这样做, helperText={errors.email?.message} 但打字稿抱怨这个作业。

Property 'email' does not exist on type 'NestDataObject<FormData>'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

我不想从我的 .eslintrc 文件中禁用此规则,因为它可能会忽略我的应用程序中的其他类似问题,而这在某些地方可能是需要的。将react-hook-form的错误消息作为helperText分配给material-ui组件的正确方法是什么?

codesandbox 链接 https://codesandbox.io/s/material-ui-react-form-hook-yi669

Mah*_*esh 4

需要为表单数据定义一个数据类型并将其传递给“useForm”。

type FormData = {
  email: string;
  password: string;
};

const { control, handleSubmit, errors } = useForm<FormData>();
Run Code Online (Sandbox Code Playgroud)

更新的沙箱:https://codesandbox.io/s/material-ui-react-form-hook-answer-8cxc1

  • @Mahesh,您好,我使用了上面的代码,但得到的错误是“类型‘UseFormReturn&lt;FormData&gt;’.ts(2339) 上不存在属性‘错误’” (3认同)