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

Che*_*eng 11 reactjs react-bootstrap

我想出了如何使用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>
Run Code Online (Sandbox Code Playgroud)

但是我怎么想为onSelect编写处理程序以捕获被选中的选项?我试过这个,但不知道在里面写些什么:

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

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

谢谢!

nov*_*yak 20

onSelect函数传递给选定的值

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

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

所以在你的代码中

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

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

  • 不要劫持这个问题,但这对我不起作用,我得到`SyntheticMouseEvent {dispatchConfig:Object,dispatchMarker:".0.2.0.1.0.0.0.0.1.$ = 11:0.$ = 11:0.0" ,nativeEvent:MouseEvent,在尝试记录evt时输入:"click",target:a ...}` (3认同)
  • 嗯,我认为问题是这些是菜单项.期望是当用户从下拉列表中选择某些内容时应该发生某些事情.它没有当前值的概念.如果你想要一个像元素的表单,用户可以选择一个选项,然后继续你可能想看一个<输入> (2认同)
  • 在反应中,setState不是同步操作(来自docs)setState()不会立即改变this.state,而是创建一个挂起状态转换.调用此方法后访问this.state可能会返回现有值.无法保证对setState的调用进行同步操作,并且可以对调用进行批处理以获得性能提升.如果之后需要执行某些操作,请将回调作为setstate的第二个参数传递. (2认同)

小智 5

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

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

  • 实际上,它是相反的......函数应该是`handleSelect: function (evtKey, event) {....` 参考:https://react-bootstrap.github.io/components/dropdowns/ (2认同)