如何在 React JS 编辑表单中的选择下拉列表中显示所选选项

2023-12-24

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

{
  UUID: "xxxxxx-bd10-473e-a765-xxxxxx"
  address1: "addr1"
  address2: "addr2"
  address3: ""
  city: "xxxxx"
  contact: "uxxxxxb"
  country: "xxxxxx"
  email: "[email protected] /cdn-cgi/l/email-protection"
  links: {Company: 'xxxxxx-4689-4689-8812-xxxxxxxxx'}
  name: "xxxxx"
  phone: "xxxxxxxx"
  state: "xxxxxxxx"
  zip: "11111"
}

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

    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>
            </>

  }

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


来自react-hook-form您必须使用的文档setValue or reset钩子的方法,setValue只会设置您指定的字段的值,并且reset将重置整个表单并设置您指定的初始值

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

https://react-hook-form.com/api/useform/reset 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);
      })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 React JS 编辑表单中的选择下拉列表中显示所选选项 的相关文章

随机推荐