我有困难,将 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
功能工作?我在此场景的文档中找不到答案。
最佳答案
在 react-hook-form
v7,这是您注册输入的方式:
<input {...register('name')} />
调用 register()
将为您的输入返回必要的 Prop ,如 onChange
, onBlur
和 ref
.这些 Prop 让 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}
/>
现场演示关于reactjs - 使用 material-ui TextField 进行最新的 react-hook-form 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67009085/