【发布时间】:2022-11-22 17:22:12
【问题描述】:
我正在为我的项目使用 react-hook-form 验证。我有一个选择选项,当它发生变化时,我将所选选项的值设置为另一个输入,即客户,但是当我提交表单时,客户值显示为空,如何解决这个问题?
这是我的代码
function App() {
const [inputs, setInputs] = useState();
const [inputs1, setInputs1] = useState();
const {
register,
formState: { errors },
trigger,
handleSubmit
} = useForm({
defaultValues: {
searchby: "searchby",
customers: "",
firstName: ""
}
});
const onSubmit = (data) => {
alert(JSON.stringify(data));
};
const handleInputChanges = (event) => {
const name = event.target.name;
const value = event.target.value;
setInputs(value);
setInputs1(value);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<select
name="searchby"
{...register("searchby", {
required: "password is required."
})}
value={inputs}
onChange={handleInputChanges}
>
<option selected value="searchby">
Search By
</option>
<option value="customerID">Custimer ID </option>
<option value="teleco">Teleco</option>
</select>
{errors.searchby && <p>This field is Required</p>}
<label>Customer: </label>
<input
name="customers"
{...register("customers")}
value={inputs1}
onChange={handleInputChanges}
/>
{errors.customers && <p>This field is Required</p>}
<label>First name: </label>
<input {...register("firstName", { required: true })} />
{errors.firstName && <p>This field is Required</p>}
<input type="submit" />
<button
type="button"
>
Validate All
</button>
</form>
);
}
这是我提交表格时得到的
代码链接:codesandbox.io
【问题讨论】:
-
在 react-hook-form 版本 7.16.0 及以上你可以这样做:github.com/react-hook-form/react-hook-form/releases/tag/v7.16.0