如何验证React Hook形式选择字段
选择任何选项后,我可以在onChange < /code>函数上获取值,但是 /我尝试提交表单时出现错误消息。
我的代码:
<div className="form-group mb-3">
<label>Country</label>
<Controller
control={control}
name="country"
render={({
field: { onChange, onBlur, value, ref }
}) => (
<select
className='form-control form-select'
onChange={(e) => setCountry(e.target.value)}
inputRef={register("country", { required: true })}
>
<option>Select Country</option>
{
Country.getAllCountries().map((item) => <option value={item.isoCode} key={item.isoCode}>{item.name}</option>)
}
</select>
)}
/>
{errors.country && <span className="error-text">Country is required</span>}
</div>
错误消息:
I'm able to get the value on the onChange
function after I select any option, but an error message appears when /I try to submit the form.
My code:
<div className="form-group mb-3">
<label>Country</label>
<Controller
control={control}
name="country"
render={({
field: { onChange, onBlur, value, ref }
}) => (
<select
className='form-control form-select'
onChange={(e) => setCountry(e.target.value)}
inputRef={register("country", { required: true })}
>
<option>Select Country</option>
{
Country.getAllCountries().map((item) => <option value={item.isoCode} key={item.isoCode}>{item.name}</option>)
}
</select>
)}
/>
{errors.country && <span className="error-text">Country is required</span>}
</div>
Error message:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用React-Hook-Form的控制器使用控制器时,这是正确的方法:
如果您没有任何特殊原因,请勿将
field
删除,并使用fieldState
在Controller提供的中的值与呈现的字段相关。
This is the right way when your using Controller from react-hook-form:
If you don't have any special reasons do not desagregate
field
and use the values infieldState
provided byController
they are related to the field rendered.