1

鉴于在 react-select ( https://jedwatson.github.io/react-select/ ) 中进行的选择,我正在使用 axios ( https://github.com/mzabriskie/axios ) 从远程 url 中获取数据为了在页面上填充第二个 react-select。

诀窍是我认为我的用例与 Async 示例不同的地方在于,我不希望用户必须在第二个选择中键入以触发自动填充。我希望当数据从 AJAX 调用返回时立即发生自动填充

我已经确认我正确地获取了远程数据,但是我不能完全弄清楚loadOptionsreact-select 参数的正确语法。代码中与我想要的最接近的示例是项目示例中的此函数

https://github.com/JedWatson/react-select/blob/master/examples/src/components/GithubUsers.js#L36

感谢您提供的任何提示

4

2 回答 2

1

看起来您正在尝试执行相关的选择类型的场景,其中传递了第二个选择将使用的附加参数,并且您需要打开新选项。

我通过覆盖 AsyncSelect 并调整我的 loadOptions 来做到这一点(使用当前版本)。

import Select from 'react-select/lib/Async';

export default class AsyncSelect extends Select {
  /**
   * reload()
   * Called when optional load arguments change, to reload the
   * data from remote source with new options
   * loadOptions={
   *  (inputValue) => this.props.loadOptions(
   *      inputValue,
   *      this.props.loadArguments
   *    )
   *  }
   */
  reload() {
    this.loadOptions('', options => {
      const isLoading = !!this.lastRequest;
      this.setState({ defaultOptions: options || [], isLoading });
    });
  }

  componentWillReceiveProps(nextProps) {
    // if the cacheOptions prop changes, clear the cache, force a reload
    if (nextProps.cacheOptions !== this.props.cacheOptions) {
      this.optionsCache = {};
    }
    /**
     * loadArguments
     * Optional property used in the remote request.
     * If these change externally, then the options should be reloaded.
     * This is handy for things like related selects.
     */
    if (nextProps.loadArguments !== this.props.loadArguments) {
      this.reload();
    }
    if (nextProps.defaultOptions !== this.props.defaultOptions) {
      this.setState({
        defaultOptions: Array.isArray(nextProps.defaultOptions)
          ? nextProps.defaultOptions
          : undefined
      });
    }
  }
}

然后,在我的组件中:

const {loadArguments, myLoadFunc, ...attributes} = this.props;
return (
  <AsyncSelect
    {...attributes}
    className={classes}
    defaultOptions
    loadArguments={loadArguments}
    loadOptions={(inputValue) => myLoadFunc(inputValue, loadArguments)}
    value={selected}
    onChange={this.onChange}
  />
);
于 2018-10-11T16:33:55.687 回答
0

在 github 异步示例中,输入参数getUsers(input)是搜索文本。

您可以将您的第一个 react-select 值存储在组件状态中,而不是 loadOptions 承诺将使用此状态值获取端点firstSelectValue

getUsers() {
   return fetch(`https://api.github.com/search/users?q=${this.state.firstSelectValue}`)
     .then((response) => response.json())
     .then((json) => {
        return { options: json.items };
    });
}
于 2017-11-18T10:34:09.460 回答