reactjs 使用react-select和react-hook-form返回正确的值

v9tzhpje  于 2022-12-12  发布在  React
关注(0)|答案(7)|浏览(166)

我正在使用react-hook-forms Controller API围绕react-select中的AsyncSelect来加载选项,作为用户从外部API输入的类型。除了返回值是字符串"[object Object]"而不是对象的fullName属性之外,一切都正常。
我的元件:

<Controller
            control={control}
            name="businessCategory"
            as={
              <AsyncSelect
                className="react-select-container"
                loadOptions={v => handleAutocompleteLookup(v)}
                onChange={handleCategoryInputChange}
                getOptionLabel={option => option.name}
                getOptionValue={option => option.fullName}
              />
            }
          />

我的handleChange函数. setValue是从react-hook-form中得到的:

const handleCategoryInputChange = newValue => {
    return setValue('businessCategory', newValue, true);
  };

任何my data都是具有以下形状的对象数组:

{
  fullName: "DJ service"
  id: "gcid:dj"
  name: "DJ service"
  publisher: "GMB"
}

任何关于这方面的线索都将不胜感激,谢谢!

eivnm1vs

eivnm1vs1#

按以下方式更新代码

在您的汇入中

import { useForm, Controller } from 'react-hook-form';
import Select from 'react-select';

在挂钩组件中

function Yourcomponent(props){

    const methods = useForm();
    const { handleSubmit } = methods;
    

    const options = [
     { value: '1', label: 'Apple'},
     { value: '2', label: 'Ball'},
     { value: '3', label: 'Cat'},
    ];
    
    const default_value = 1; // you can replace with your default value
    

    // other codes of the component 
    

    function submitHandler(formData){
    
    // values are available in formData

    }

    return(
      <div>
        
        {* other part of your component *}
        <form onSubmit={handleSubmit(submitHandler)} >

           {* other part of your form *}
            <Controller
                control={methods.control}
                defaultValue={default_value}
                name="field_name_product"
                render={({ onChange, value, name, ref }) => (
                    <Select
                        inputRef={ref}
                        classNamePrefix="addl-class"
                        options={options}
                        value={options.find(c => c.value === value)}
                        onChange={val => onChange(val.value)}
                    />
                )}
            />

           {* other part of your form *}
        </form>

        {* other part of your component *}
      </div>
    )
}
b09cbbtk

b09cbbtk2#

对于多选(与react-hook-form v7一起使用):

import Select from "react-select";
import { useForm, Controller } from "react-hook-form";

const {
  control
} = useForm();

<Controller
  control={control}
  defaultValue={options.map(c => c.value)}
  name="options"
  render={({ field: { onChange, value, ref }}) => (
    <Select
      inputRef={ref}
      value={options.filter(c => value.includes(c.value))}
      onChange={val => onChange(val.map(c => c.value))}
      options={options}
      isMulti
    />
  )}
/>
wfveoks0

wfveoks03#

我是这样做的:
第一个

2j4z5cfb

2j4z5cfb4#

好吧,实际上这些答案中的大多数都不适用于您有一个自定义onChange函数的情况。诀窍(看起来像是一个bug)是首先设置“onChange(瓦尔.value)”内联,然后设置您的状态变量。下面是我的完整代码;

import { useForm, Controller } from "react-hook-form";
   const {
       register,
       control,
       formState: { errors },
       handleSubmit,
    } = useForm();

   const handleChangeType = (option) => {
      setItemType(option);
      var options = getOptions(option.value); 
      setList(options);
      setGender(null);
   }; 

    <Controller
      control={control}
      name="itemType"
      rules={{
         required: {
            value: assetType.value == "item",
            message: "Item type is required.",
         },
      }}
      render={({ field: { onChange, value, ref, name } }) => (
         <Select 
            className={"react-select"}
            classNamePrefix={"react-select"}
            placeholder={"Item type"} 
            options={itemTypeList}  
            onChange={val => {
                onChange(val.value);
                handleChangeType(val); 
            }} 
         />
      )}
   /> 
   {errors.item?.message && <div class="validationText">{errors.item?.message}</div>}
wnrlj8wa

wnrlj8wa5#

import Select from "react-select";
import { useForm, Controller } from "react-hook-form";
const options = [
     { value: '1', label: 'Apple'},
     { value: '2', label: 'Ball'},
     { value: '3', label: 'Cat'},
    ];
const {control} = useForm();
<Controller
 control={control}
 name="AnyName"
 render={({ field: { onChange, value, name, ref } }) => (
        <Select
        inputRef={ref}
        classNamePrefix="addl-class"
        options={options}
        value={options.find((c) => c.value === value)}
        onChange={(val) => onChange(val.map((c) =>c.value))}
        isMulti
        />
        )}
/>
s71maibg

s71maibg6#

通过react-hook-form使用自定义寄存器来解决此问题,如下所示:
https://react-hook-form.com/get-started#Registerfields

ff29svar

ff29svar7#

我想发布适合我的内容,我使用了react-selectreact-hook-form和**@hookform/error-message**:
我创建了一个函数,如下所示

const handleCategoryInputChange = (newValue: any) => {
    console.log(newValue.value);
    return setValue('contract', newValue.value);
  };

我的react select如下所示:

<Controller
  name="contract"
  control={control}
  rules={{ required: true }}
  render={({ field: { onChange, value, name, ref } }) => (
    <ReactSelect
     // value={contractData.find((c) => c.value === value)}
     // onChange={(val) => onChange(val)}
     onChange={handleCategoryInputChange}
     options={contractData}
     ref={ref}
     name={name}
     defaultValue={contractData[0]}
     theme={customTheme}
     isSearchable={false}
     className="block w-full min-w-0 flex-1 sm:text-sm"
/>
)}
/>
<ErrorMessage errors={errors} name="contract" message="Select a Contract" />

我不认为我的className工作正常,你可以忽略这部分。它是为我的具体设置工作,虽然哈哈。注解掉的代码没有工作的方式,我想要的,因为当我控制台记录的数据,我得到了它如下:

contract: {label: 'contract name', value: 'contract name'}
optionPeriods: "dfd"
performanceEndDate: "2022-12-08"
performanceStartDate: "2022-12-08"
proposalDueDate: "2022-12-08T12:54"
requirements: "dfd"
trackingNumber: "dfd"

因此,我对该特定解决方案进行了注解,并按照您现在看到的方式进行了操作,我得到了我希望用于合同的确切数据,如下所示:

contract: "contract name"
optionPeriods: "dfd"
performanceEndDate: "2022-12-08"
performanceStartDate: "2022-12-08"
proposalDueDate: "2022-12-08T12:54"
requirements: "dfd"
trackingNumber: "dfd"

我希望这能帮上忙

相关问题