如何在 React JS 编辑表单的选择下拉列表中显示选定的选项 [英] How to display selected option in select dropdown in React JS edit form

查看:35
本文介绍了如何在 React JS 编辑表单的选择下拉列表中显示选定的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的编辑数据表单使用 react-hook-form npm 模块.下面是我的 API 响应示例:

I am using react-hook-form npm module for my edit data form. Here below is my API response sample:

{
  UUID: "xxxxxx-bd10-473e-a765-xxxxxx"
  address1: "addr1"
  address2: "addr2"
  address3: ""
  city: "xxxxx"
  contact: "uxxxxxb"
  country: "xxxxxx"
  email: "xxxxxx@email.com"
  links: {Company: 'xxxxxx-4689-4689-8812-xxxxxxxxx'}
  name: "xxxxx"
  phone: "xxxxxxxx"
  state: "xxxxxxxx"
  zip: "11111"
}

下面是编辑组件所需的代码行

Here below is the required code lines from the edit component

    import axios from 'axios'  
    import { useForm } from 'react-hook-form'
    // Now getting the default list of all the companies
    Edit.getInitialProps = async (context) => {
      try {
        const companyResponse = await axios(process.env.BASE_URL + '/v1/companies',{
            headers : {
                'Content-Type': 'application/json',
                'Authorization' : 'Bearer ' + process.env.TOKEN
            }
        })
        if(companyResponse.status == 200) {
            return {
                companies : companyResponse.data.results
            }
        } else {
            return {companies: []}
        }
    } catch (error) {
        return {companies: []}
    }
  }
  
  export default function Edit({...props}) {

      const [selectedCompany, setSelectedCompany] = useState(0)

      const {
        register,
        handleSubmit,
        reset,
        formState: { errors },
      } = useForm({mode: 'onBlur' });
      

      useEffect(() => {
          // Here I am getting location existing value from API response i.e. the above json response
          setSelectedCompany(locationDetails.links.Company)  // setting state of existing company of location
      })

      return (

               <>
                <form className="g-3" onSubmit={handleSubmit(editLocation)} data-testid="editLocationForm">
                   <select {...register('company', { required: true })} className="form-control">
                   {(props.companies || []).map((company, index) => (
                    <option key={index} value={company.UUID} defaultValue={company.UUID === selectedCompany}>{company.name}</option>
                 ))}
               </select>


                .....
                </form>
            </>

  }

我需要显示下拉列表中选择的公司名称的现有值.

I need to display the existing value of company name as selected in the drop down.

推荐答案

react-hook-form 文档中,您必须使用 setValuereset 方法,setValue 只会设置你指定的字段的值,reset 会重置整个表单并设置你的初始值指定

From the react-hook-form documentation you have to use the setValue or reset methods of the hook, the setValue will only set the value of the field you specify, and the reset will reset the whole form and set initial values that you specify

https://react-hook-form.com/api/useform/setvalue

https://react-hook-form.com/api/useform/reset

设置值方法

useEffect(() => {
          // Here I am getting location existing value from API response i.e. the above json response
          setSelectedCompany(locationDetails.links.Company)  // setting state of existing company of location
          setValue('company', locationDetails.links.Company);
      })

重置方法

useEffect(() => {
          // Here I am getting location existing value from API response i.e. the above json response
          setSelectedCompany(locationDetails.links.Company)  // setting state of existing company of location
          reset('company', locationDetails.links.Company);
      })

这篇关于如何在 React JS 编辑表单的选择下拉列表中显示选定的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆