Typescript下使用React-Hook-Form如何获取React-Select仅value值
问题原因
react-select 组件的 onChange 回调默认返回完整的选中选项对象,你直接将 react-hook-form 提供的 field.onChange 透传,就会导致表单存储整个对象而非仅 value 值。
解决方法
只需要对 Select 的 onChange 做一层封装,仅将选中项的 value 传递给 react-hook-form 即可,其余逻辑无需改动。
修改后的核心代码如下:
const { handleSubmit, control, formState:{errors}} = useForm<IAddProductForm>(); const handleOnSubmit = (data:IAddProductForm) => { console.log(data); // 此时category字段为字符串类型的value值 } const categoryOptions = [ {value:"Grocery", label:"Grocery"}, {value:"Pharmacy", label:"Pharmacy"}, {value:"Electronic", label:"Electronic"}, {value:"Food", label:"Food"}, ]; return( <React.Fragment> <Form onSubmit={handleSubmit(handleOnSubmit)}> <Controller control={control} render={({field:{onChange, value, name, ref}}) => ( <Select inputRef={ref} // 这里保持原逻辑不变,因为react-select需要接收完整选项对象作为value value={categoryOptions.find(c => c.value === value)} options={categoryOptions} // 仅修改onChange,提取选中项的value传递给react-hook-form onChange={(selectedOption) => onChange(selectedOption?.value)} /> )} name="category" /> <Button type="submit">submit</Button> </Form> </React.Fragment> );
补充说明
如果你的场景是多选的react-select,只需要调整onChange的取值逻辑即可:
onChange={(selectedOptions) => onChange(selectedOptions?.map(opt => opt.value))}
同时你可以将 IAddProductForm 里的 category 字段直接定义为 string(单选)或 string[](多选)类型,无需定义为选项对象类型,符合Typescript类型规范。
内容的提问来源于stack exchange,提问作者Jeewantha Lahiru
相关产品推荐
相关产品推荐

