我创建了一个React Hook窗体和一个div
来显示数据。我想将输入值显示为用户类型。我可以使用onChange
来实现这一点,但我在使用react-hook-form
时遇到了一个问题。
如果我尝试在{...register()}
之后添加onChang
e,它会工作,但是如果输入为空,错误消息不会消失。有没有可能的方法来做到这一点?
import "./styles.css";
import { useState } from "react";
import { useForm } from "react-hook-form";
const initalState = {
name: "test",
description: "test description"
};
export default function App() {
const [info, setInfo] = useState(initalState);
const handleFormSubmit = (data) => {
setInfo(data);
console.log(data);
};
const handleFormChange = (event) => {
console.log(event.target.value);
setInfo({
...info,
[event.target.name]: event.target.value
});
};
return (
<div className="App">
<div style={{ textAlign: "left" }}>
<p>Name: {info.name}</p>
<p>Description {info.description}</p>
</div>
<Form
handleFormSubmit={handleFormSubmit}
handleFormChange={handleFormChange}
/>
</div>
);
}
const Form = ({ handleFormSubmit, handleFormChange }) => {
const {
register,
handleSubmit,
formState: { errors }
} = useForm();
return (
<form onSubmit={handleSubmit(handleFormSubmit)}>
<label htmlFor="name">Name: </label>
<input id="name" {...register("name", { required: "Can't be blank" })} />
<p style={{ color: "red" }}>{errors.name?.message}</p>
<label htmlFor="description">Description: </label>
<input
id="description"
{...register("description", { required: "Can't be blank" })}
/>
<p style={{ color: "red" }}>{errors.description?.message}</p>
<button type="submit">Submit</button>
</form>
);
};
1条答案
按热度按时间fykwrbwg1#
订阅可以使用
useForms()
返回的watch
函数,首先将handleFormChange
修改为:然后,在
Form
组件中,执行以下操作: