Achieve combobox behavior for react-bootstrap-typeahead

旧时模样 提交于 2019-12-02 06:59:05

问题


I'm trying to use the react-bootstrap-typeahead control but I'm struck trying to make it do what I want. I've actually got 2 of these on my page, one of which is doing a true async lookup, and one which I almost want to behave like a combobox.

What I'd like to be able to do is to select an item, then click the dropdown to change my mind and choose another item. However if you try this, when you expand the list again it's automatically filtered to just the item you have selected.

For example if I use the basic example on the demo page, and select Alabama, clicking the input now only displays Alabama and none of the other choices. I'd like this to ideally return me to the full list (is this possible?).


回答1:


Yes, it's possible. The filterBy prop can take a custom function, allowing you to filter results however you want. So building off the example you linked to, you'd want to do something along these lines:

<Typeahead
  filterBy={(option, text) => {
    if (this.state.selected.length) {
      // Display all the options if there's a selection.
      return true;
    }
    // Otherwise filter on some criteria.
    return option.name.toLowerCase().indexOf(text.toLowerCase()) !== -1;
  }}
  labelKey="name"
  onChange={(selected) => this.setState({selected})}
  options={options}
  placeholder="Choose a state..."
  selected={this.state.selected}
/>

Update As of v3.0.0, the filterBy callback passes props instead of text:

(option, props) => {
  if (props.selected.length) {
    // Display all the options if there's a selection.
    return true;
  }
  // Otherwise filter on some criteria.
  return option.name.toLowerCase().indexOf(props.text.toLowerCase()) !== -1;
}


来源:https://stackoverflow.com/questions/46184159/achieve-combobox-behavior-for-react-bootstrap-typeahead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!