【问题标题】:how to hide empty label in react-bootstrap-typeahead如何在 react-bootstrap-typeahead 中隐藏空标签
【发布时间】:2019-07-06 12:04:50
【问题描述】:

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

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

我使用了道具 emptyLabel="",它给了我如下所示的结果

在这两种情况下,当我按 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>

【问题讨论】:

  • 你能否提供更多细节,比如分享一些你遇到问题的代码sn-p。
  • @MonikaMangal 编辑问题以包含代码。
  • @JacobNelson 你用的是什么版本?
  • 我不太确定版本。但是从 package.json,我得到了这个数字 4.0.0-alpha.10

标签: reactjs react-bootstrap-typeahead


【解决方案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
  ...
  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

【讨论】:

  • 谢谢,埃里克。让我试试这个解决方案。
  • 嗨 Eric,我尝试了这个解决方案,但出现以下错误。 Error: One or more options does not have a valid label string. Check the labelKey prop to ensure that it matches the correct option key and provides a string for filtering and display. 请帮我解决这个问题。
  • 嗨 Eric,更新:将 labelKey="name" 添加到 TypeaheadMenu 解决了上述错误。但是,在按下 ENTER 键时,表单没有被提交。我现在正在调查。
  • 嗨,埃里克,在进行此更改后,我最终出现以下错误,Warning: Failed prop type: The prop search is marked as required in Highlighter, but its value is undefined. in Highlighter (created by TypeaheadMenu)
  • @JacobNelson:使用附加代码和实时示例更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
相关资源
最近更新 更多