如何捕获 React-Bootstrap 下拉列表的值?

问题描述 投票:0回答:4

我想出了如何使用react-bootstrap来显示下拉列表:

<DropdownButton bsStyle="success" title="Choose" onSelect={this.handleSelect} >
    <MenuItem key="1">Action</MenuItem>
    <MenuItem key="2">Another action</MenuItem>
    <MenuItem key="3">Something else here</MenuItem>
</DropdownButton>

但是我该如何编写 onSelect 的处理程序来捕获正在选择的选项呢?我尝试了这个,但不知道里面写什么:

handleSelect: function () {
    // what am I suppose to write in there to get the value?
},

还有,有没有办法设置默认选择的选项?

reactjs react-bootstrap
4个回答
37
投票

onSelect
函数传递所选值

<DropdownButton title='Dropdowna' onSelect={function(evt){console.log(evt)}}>
  <MenuItem eventKey='abc'>Dropdown link</MenuItem>
  <MenuItem eventKey={['a', 'b']}>Dropdown link</MenuItem>
</DropdownButton>

在这种情况下,如果您选择第一个选项,则会打印“abc”,在第二个选项中您可以看到也可以传入一个对象。

所以在你的代码中

handleSelect: function (evt) {
    // what am I suppose to write in there to get the value?
    console.log(evt)
},

我不确定默认值是什么意思,因为这不是一个选择 - 按钮文本是标题属性中的任何内容。如果你想处理默认值,你可以在值为

null
时设置一个值。


4
投票

您忘记提及 eventKey 作为第二个参数传递,这是获取您单击的值的正确形式:

handleSelect: function (evt,evtKey) {
    // what am I suppose to write in there to get the value?
    console.log(evtKey)
},

1
投票

您可能需要针对您的情况使用 FormControl >> 选择组件:

  <FormControl componentClass="select" placeholder="select">
        <option value="select">select</option>
        <option value="other">...</option>
  </FormControl>

1
投票

您应该按如下方式更改handleSelect签名(在组件类中):

handleSelect = (evtKey, evt) => {
    // Get the selectedIndex in the evtKey variable
}

要设置默认值,您需要使用

title
 上的 
DropdownButton

属性

参考:https://react-bootstrap.github.io/components/dropdowns/

© www.soinside.com 2019 - 2024. All rights reserved.