使用react select中的asyncselect的react钩子窗体

tzcvj98z  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(410)

处理从api加载选项的react-select asyncselect组件的问题。但是我无法通过控制器将信息传递给react-hook表单。asyncselect工作得非常好。数据在我的“SelectedValue”状态下很好地返回。有人能帮我吗?

const [inputValue, setValue] = useState('');
    const [selectedValue, setSelectedValue] = useState(null);
    // handle input change event
    const handleInputChange = value => {
        setValue(value);
    };
    // handle selection
    const handleChange = value => {
        setSelectedValue(value);
    }
const loadOptions = async (inputValue, callback) => {

        const response = await fetch(`APIurl`);
        const json = await response.json();
        const object = json.records;
        callback(object.map(i => ({ label: `${i.fields.firstName} - ${i.fields.lasName} , value: i.fields.firstName })))
    }
<Controller
   name="company"
   control={control}
   rules={{ required: true }}
   render={({ field: { onChange, value } }) => (
       <AsyncSelect
         isClearable
         value={selectedValue}
         placeholder={'Your information'}
         loadOptions={loadOptions}
         onInputChange={handleInputChange}
         onChange={handleChange}
         styles={customStyles}
       />)}
/>
iezvtpos

iezvtpos1#

react-hook-form 为您管理一些常见的事件和状态(如value、onchange、onblur等),因此在大多数情况下无需定义自己的状态,除了 onInputChange 在里面 AsyncSelect .
您可以尝试选择该选项并提交表单。

<Controller
    name="company"
    control={control}
    rules={{ required: true }}
    render={({ field }) => (
    <AsyncSelect
        {...field}
        isClearable
        defaultOptions
        placeholder={"Your information"}
        loadOptions={loadOptions}
        onInputChange={handleInputChange}
        // styles={customStyles}
    />
    )}
/>

这是代码沙盒

相关问题