如何从react-hook-form与antd Select中同时获取选中项的id和label值
问题原因
当前你代码中的Ant Design Select默认将<Option>的key属性作为选中值返回,因此react-hook-form存储的customer字段仅包含选中项的id,无法直接获取对应的term值,可通过以下两种方案解决:
方案1:表单直接存储完整选中对象(推荐)
该方案无需额外查询,直接从表单取值即可同时获取id和term,改动点如下:
- 显式给
<Option>设置value为包含id和term的对象,新增label属性适配搜索功能 - 给Select添加
optionFilterProp="label"属性,保证下拉搜索过滤逻辑正常 - 调整表单初始值格式匹配存储结构
修改后核心代码:
import React from 'react' import { useForm, Controller } from 'react-hook-form' import { Select } from 'antd' const { Option } = Select export default function PatientRegistrationForm({ options }) { const { register, handleSubmit, getValues, control, formState: { errors } } = useForm({ defaultValues: { customer: {id: '', term: ''}, // 调整初始值为对象格式 } }) const children = [] for (const {id, pt: {term}} of options){ // 显式设置value为完整对象,新增label属性 children.push(<Option key={id} value={{id, term}} label={term}>{term}</Option>) } // 直接获取完整选中对象 const selectedCustomer = getValues("customer") const customer = { customerId: selectedCustomer.id, customerName: selectedCustomer.term } return ( <div className=""> <form onSubmit={handleSubmit(onSubmit)} className=""> <section> <Controller control={control} name="customer" render={({ field }) => ( <Select {...field} defaultValue="" bordered={true} filterOption={true} optionFilterProp="label" // 新增该属性,按label搜索 className="form-control" > { children } </Select> )} /> </section> </form> </div> ); }
方案2:仍存储id,通过id匹配对应term
如果不想改动原有表单字段的存储格式,可保留id存储逻辑,取值时通过id从options数组中匹配对应的term:
const retrievedID = getValues("customer") // 匹配对应选项 const matchedItem = options.find(item => item.id === retrievedID) const customer = { customerId: retrievedID, customerName: matchedItem ? matchedItem.pt.term : '' }
注:你原有代码中
customer对象的键值对错误使用了等号=,需要改为冒号:。
内容的提问来源于stack exchange,提问作者user13171920
相关产品推荐
相关产品推荐

