如何从 react hook form 和 antd 中获取表单值和标签 Select

how to retrieve form values and labels from react hook form and antd Select

我正在使用 antd Select 并通过 'Controller' 响应钩子形式。我正在从具有结构的获取数据中填充 Select 选项;

{ { “编号”:“232342”, “术语”:“你好” } { “编号”:“232342”, “术语”:“你好” } }

Select 组件正确显示供选择的术语。但是,我想检索所选的 'id' 和 'term' 并用它来填充另一个 json 对象。

getValues(" ") 仅检索 'id'。我如何检索和访问 'id' 和 '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 的回答。我知道已经有一段时间了,但我想把它放在这里以防它帮助别人。事实证明它与 React Hook 形式关系不大。 Ant design select 组件有一个 prop 'labelInValue' 其中 returns 一个包含标签和值的对象。