如何从react-hook-form和antd-Select中检索表单值和标签



我通过"控制器"使用antd选择和反应钩子形式。我正在从具有结构的提取数据中填充Select选项;

{{"id":"232342〃;,"术语":"你好";}{"id":"232342〃;,"术语":"你好";}}

"选择"组件正确显示要选择的术语。然而,我想检索所选对象的"id"one_answers"term",并使用它来填充另一个json对象。

getValues("(只检索"id"。如何检索和访问"id"one_answers"term"。

这是代码的一部分:

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: "",
}
})
const children = []
for (const {id, pt: {term}} of options){
children.push(<Option key={id}>{term}</Option>)
}

// Define the retrieved values from the form
const retrievedID = getValues("customer")

// Use the retreived values to populate this object
const customer = {
customerId = retrievedID
customerName = "nothing happens here"
},

return (
<div className="">
<form onSubmit={handleSubmit(onSubmit)} className="">

<section>
<Controller
control={control}
name="customer"
render={({ field }) => (
<Select {...field} defaultValue=""
bordered={true}
filterOption={true}
className="form-control"

>
{ children }
</Select>
)} 
/>
</section>
</form>
</div>

);
}

提前感谢您的帮助。

您必须使用以下内容手动检索选项:

const retrievedID = getValues("customer")
const retrievedOption = options.find(option => option.id === retrievedID)
const customer = {
customerId: retrievedID,
customerName: retrievedOption.term
}

感谢#sgarcia.dev的回答。我知道已经有一段时间了,但我想把它放在这里,以防它帮助别人。Ant设计选择组件有一个prop"labelInValue",它返回一个包含标签和值的对象。

最新更新