首页 > 解决方案 > react-hook-forms 未使用 defaultValue 验证 react-select 控件

问题描述

我正在使用 react-hook-form 处理表单,我需要一个可搜索的选择,所以我使用 react-select 创建了一个组件。我的问题是,我在加载时传递了一个默认值,如果我用来验证该字段,我会在..trigger()上得到一个无效值。它会提取正确的值。如果我在下拉列表中选择一个新值,它会起作用。 . 只是不接受默认值..<Select>getValues()

如果有人有时间看一下,我创建了一个沙盒?

标签: reactjsreact-selectreact-hook-form

解决方案


将您的默认值放在defaultValuesreact-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)}
/>

现场演示

Codesandbox 演示


推荐阅读