使用 Elasticsearch 强制 react-select 显示所有选项

Force react-select to show all options using Elasticsearch

我正在尝试使用 elasticsearch 实现它并且它正在运行但是我如何才能强制显示可能与搜索词不同的结果?例如,我搜索 ardino,elasticsearch 给了我 arduino 这个词,但是 react-select 没有显示那个结果,因为 ardino 不包含 arduino。我知道这个库的想法就是这样,它工作正常,但我已经实现了大部分内容,只是缺少那部分。

句柄给出了正确的行为并且正确地填充了选项。

谢谢

<Select
  name= {this.state.selectedOption}
  value={this.state.selectedOption}
  isSearchable={true}
  onChange = {(val) => {

    this._handleSearch(val.value)
  }}
  onInputChange = {(val) => {

    this._handleSearch(val)
  }}
  options={this.state.options}
/>

我建议使用 Async component,它可以简化您的代码。您将不再需要 onChange 处理程序。

isSearcheabletrue by default,无需指定。

回答您的问题:确保您在每个结果选项中传入 labelvalue 键。如果您想自定义任何结果,例如在结果中添加搜索词,您可以手动操作 options 数组。

import React, {Component} from 'react';
import AsyncSelect from 'react-select/lib/Async';

class Search extends Component {

    state = {inputValue: ""}

    onInputChange = (inputValue) => {
        this.setState({ inputValue });
    };

    getSearchResults = async (inputValue) => {
        // elastic search results
        let options = await fetch(`searchElastic/${inputValue}`);

        // input value of drop-down
        const inputValue = this.state.inputValue;

        // manually add input field as an option in drop-down
        if (inputValue.length > 0)
            options.unshift({label: inputValue, value: inputValue})

        // async handling of new props
        return options.map(opt => {
            return {label: opt.name, value: opt.value}
        })
    }

    render() {
        return <AsyncSelect
            onInputChange={this.onInputChange}
            loadOptions={this.getSearchResults}
        />
    }
}

export default Search;