带输入字段的下拉菜单

Dropdown with input field

我正在使用 react-bootstrap 向我的应用程序添加 bootstrap 元素。我需要添加一个下拉按钮,其中包含一个 "labels" 列表,用户可以使用它来标记他们的项目。

我的问题是添加输入字段,以便他们可以添加 "custom" 标签。这是它目前的样子(蓝色方块是复选框):

首先我尝试了:

<Dropdown id="myDropdown">
    <Dropdown.Toggle bsStyle="warning">Label as...</Dropdown.Toggle>
    <Dropdown.Menu>
        <li onSelect={...}>
            <Checkbox onClick={...} checked={...} inline>Some label</Checkbox>
        </li>
        <li onSelect={...}>
            <Checkbox onClick={...} checked={...} inline>Some other label</Checkbox>
        </li>
        <li><input /></li>
    </Dropdown.Menu>
</Dropdown>

但是,当您单击 input 元素时,这会关闭 dropdown

所以我尝试对官方文档中显示的示例进行细微的修改(搜索“Custom Dropdown Components”并查看代码)。这允许我单击并输入 input,但现在当我在元素外部单击时下拉菜单不会关闭。


TL;DR

我如何实现一个下拉菜单,让我可以单击一个 input 字段,当您在菜单外单击时该字段也会关闭?

编辑:

为我的第二个实现添加生成的html:

<div class="dropdown btn-group">
  <button type="button" class="dropdown-toggle btn btn-warning"><i class="fa fa-check" aria-hidden="true"></i><!-- react-text: 153 --> <!-- /react-text --><!-- react-text: 154 -->Label as...<!-- /react-text --><!-- react-text: 155 --> <!-- /react-text --><span class="caret"></span></button>
   <ul class="dropdown-menu">
     <li><label class="checkbox-inline"><input type="checkbox" value="on"><span></span><!-- react-text: 162 --> Some label<!-- /react-text --></label></li>
     <li><label class="checkbox-inline"><input type="checkbox" value="on"><span></span><!-- react-text: 167 --> Some other label<!-- /react-text --></label></li>
     <li><label class="checkbox-inline"><input type="checkbox" value="on"><span></span><input type="text" value="" style="height: 17px;font-size: .9em;"></label></li>
     <li role="separator" class="divider"></li>
     <li role="presentation" class=""><a role="menuitem" tabindex="-1" href="#">Clear labels</a></li>
   </ul>
 </div>

所以我几天前找到了答案,我会 post 在这里,以防将来有人偶然发现这个 post。

您需要安装 react-overlays 并导入 ReactRootWrapper。修改示例代码(来自文档中的 Custom Dropdown Component),组件现在应该类似于:

<RootCloseWrapper onRootClose={this.setOpenStateToFalse}>
  <Dropdown id="dropdown-custom-menu" open={this.state.open} onToggle={this.toggleOpenState}>
    <CustomToggle bsRole="toggle">Custom toggle</CustomToggle>
    <CustomMenu bsRole="menu">
      <MenuItem eventKey="1">Red</MenuItem>
      <MenuItem eventKey="2">Blue</MenuItem>
      <MenuItem eventKey="3" active>Orange</MenuItem>
      <MenuItem eventKey="1">Red-Orange</MenuItem>
    </CustomMenu>
  </Dropdown>
</RootCloseWrapper>

我没有在示例中添加函数,但它们的名称说明了它们的作用。基本上 setOpenStateToFalse() 需要始终将 this.state.open 设置为 false,并且 toggleOpenState() 需要反转 this.state.open.

的当前布尔值

希望有人觉得这有用。