我在 AsyncSelect 周围使用 react-hook-forms Controller api,从 react-select 加载选项,因为用户从外部 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);
};
我的任何数据都是具有以下形状的对象数组:{
fullName: "DJ service"
id: "gcid:dj"
name: "DJ service"
publisher: "GMB"
}
任何有关这方面的线索将不胜感激,谢谢!
最佳答案
按以下方式更新您的代码
在您的导入
import { useForm, Controller } from 'react-hook-form';
import Select from 'react-select';
在你的钩子(Hook)组件中 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>
)
}
关于reactjs - 使用 react-select 和 react-hook-form 返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62795886/