20

我想出了如何使用 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?
},

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

谢谢!

4

4 回答 4

34

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)
},

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

于 2015-07-20T06:57:58.477 回答
5

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

handleSelect: function (evt,evtKey) {
    // what am I suppose to write in there to get the value?
    console.log(evtKey)
},
于 2016-06-09T04:48:19.610 回答
2

您可能希望为您的案例使用 FormControl >> 选择组件:

  <FormControl componentClass="select" placeholder="select">
        <option value="select">select</option>
        <option value="other">...</option>
  </FormControl>
于 2017-01-29T02:27:10.213 回答
0

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

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

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

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

于 2018-06-12T11:19:11.837 回答