reactjs - react-hook-forms 未使用 defaultValue 验证 react-select 控件
问题描述
我正在使用 react-hook-form 处理表单,我需要一个可搜索的选择,所以我使用 react-select 创建了一个组件。我的问题是,我在加载时传递了一个默认值,如果我用来验证该字段,我会在..trigger()
上得到一个无效值。它会提取正确的值。如果我在下拉列表中选择一个新值,它会起作用。 . 只是不接受默认值..<Select>
getValues()
如果有人有时间看一下,我创建了一个沙盒?
解决方案
将您的默认值放在defaultValues
react-hook-form 提供的道具中:
const formMethod = useForm<Address>({
defaultValues: {
state: options.find(({ value }) => value === "OH")
}
});
并移除组件中的defaultValue
道具Select
。react-hook-form 只有在知道defaultValues
. 将默认值直接传递给 与Select
根本不传递任何东西是一样的,因为它是控制验证逻辑的 react-hook-form :
<Select
{...props}
// defaultValue={options.find(({ value }) => value === props.state)}
/>
现场演示
推荐阅读
- rust - Rust SERDE 是否需要字段顺序?
- linux - 当我尝试在 Ubuntu(Linux)中下载 expo 时出现“找不到命令”
- java - 无法从字符串单元格访问单元格的数值
- javascript - 如何在Vue中显示选定值的信息
- git - 9 月 30 日 LetsEncrypt 证书到期时,Ubuntu 20.04 上的“git”是否损坏?
- blazor - Identity->Account Manage as Razor 组件,一致的 UI
- css - CSS:保持由border-radius创建的子弹的纵横比
- java - 从包含不同类对象的列表的每个对象中检索实例变量的特定值
- google-bigquery - 如何在 BigQuery 中将字符串化数组字段转换为长整数列而没有重复字段?
- c++ - 将派生类存储到向量 C++