处理从 API 加载选项的 react-select AsyncSelect 组件的问题。但我无法通过 Controller 将信息传递给 React-Hook Form。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}
/>)}
/>
最佳答案
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}
/>
)}
/>
Here is the codesandbox
关于javascript - 使用 React-Select 中的 AsyncSelect 的 React Hook 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68337318/