想要在反应选择中获取有关 inputValue 更改的选项
P粉775723722
P粉775723722 2023-09-14 13:14:36
0
2
396

我有一个react-select组件,我想添加一个功能,这样一旦有人在react-select中输入某些内容,就应该有一个api请求来获取与输入的关键字相关的项目,如何才能我这样做

P粉775723722
P粉775723722

全部回复(2)
P粉354602955

你可以做到这一点,无需任何 API 调用,只需使用过滤器方法来过滤你的选项

P粉675258598

您应该尝试从“react-select/async”查看 AsyncSelect 然后在组件中创建一个函数来从 API 加载选项,该函数应接受输入字符串和回调,并应根据输入字符串进行 API 调用。像这样的事情

const loadOptions = (inputValue, callback) => {
    // api call here
    fetch('your-api-url?${inputValue}')
      .then(response => response.json())
      .then(data => {
         // do your work here
         const options = //transform data here
         callback(options)
      });
};

然后在您的组件中将 loadOptions 函数传递到 loadOptions 属性中

const YourComponent = () => {
    return (
       <AsyncSelect
         cacheOptions
         defaultOptions
         loadOptions={loadOptions}
       />
    );
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!