如何在react-bootstrap-typeahead中隐藏空标签

时间:2019-07-04 13:20:25

标签: reactjs react-bootstrap-typeahead

我在我的一个应用程序中使用react-bootstrap-typeahead模块。除一种情况外,这工作正常。

如果没有结果,我将无法提交表格。在这种情况下,我得到了一个禁用的选项,其中未找到匹配项

enter image description here

我使用了道具emptyLabel =“”,如下所示 enter image description here

在两种情况下,当我按ESC键时,此选项都会消失,然后我就可以提交表单了。

所需的结果是摆脱此选项。任何帮助将不胜感激。

这是我的代码

<form onSubmit={this.formSubmit}>
  <Typeahead
    labelKey="name"
    flip={true}
    dropup={true}
    autoFocus={true}
    options={this.state.options}
    ref={(typeahead) => this.typeahead = typeahead}
    id="qbox"
    placeholder="Type your queries here..."
    onInputChange={this.updateText}
    onBlur={(e) => this.updateText(e.target.value, e)}
    onChange={this.valueChanged}
    maxResults={5}
    minLength={5}
  />
  <button type="submit">Submit</button>
</form>

1 个答案:

答案 0 :(得分:1)

隐藏菜单

您需要为何时呈现菜单添加自己的逻辑,因为emptyLabel的虚假值不再在v4中隐藏菜单。来自migration docs

  

此行为是在renderMenu返回null之前引入的旧解决方法。情况不再如此,现在应该使用renderMenu实现行为

如果没有结果,您可以隐藏菜单,方法是将以下内容传递给renderMenu

<Typeahead
  ...
  renderMenu={(results, menuProps) => {
    // Hide the menu when there are no results.
    if (!results.length) {
      return null;
    }
    return <TypeaheadMenu {...menuProps} options={results} />;
  }}
/>

提交表格

打开菜单时,typeahead会阻止表单提交,以防止意外提交。您可以通过添加以下内容来解决此问题:

<Typeahead
  ...
  onKeyDown={(e) => {
    // Submit the form when the user hits enter.
    if (e.keyCode === 13) {
      this.form.submit();
    }
  }}
/>

将它们放在一起

<form ref={(form) => this.form = form}>
  <Typeahead
    id="rbt-example"
    onKeyDown={(e) => {
      // Submit the form when the user hits enter.
      if (e.keyCode === 13) {
        this.form.submit();
      }
    }}
    options={options}
    placeholder="Type your queries here..."
    renderMenu={(results, menuProps) => {
      // Hide the menu when there are no results.
      if (!results.length) {
        return null;
      }
      return <TypeaheadMenu {...menuProps} options={results} />;
    }}
  />
  <button type="submit">Submit</button>
</form>

实时示例:https://codesandbox.io/s/react-bootstrap-typeahead-rtb1s