我正在使用 react-bootstrap
向我的应用程序添加 bootstrap
元素。我需要添加一个下拉按钮,其中包含用户可以用来标记其项目的“标签”列表。
我的问题是添加输入字段,以便他们可以添加“自定义”标签。这是它目前的样子(蓝色方 block 是复选框):
我首先尝试:
<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
元素时,这会关闭下拉列表
。
因此,我尝试对官方文档中显示的示例进行轻微的修改(搜索“Custom Dropdown Components ”并查看代码)。这允许我单击并输入input
,但现在当我单击元素外部时,下拉列表不会关闭。
TL;DR
如何实现一个下拉菜单,允许我单击输入
字段,当您单击菜单外部时该字段也会关闭?
编辑:
为我的第二个实现添加生成的 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>
最佳答案
所以我几天前找到了答案,我会将其发布在这里,以防将来有人偶然发现这篇文章。
您需要安装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
的当前 bool 值。
希望有人觉得这很有用。
关于javascript - 带输入字段的下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40840042/