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

24

我学会了如何使用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个回答

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时设置一个值即可。


2
嗯,我认为问题在于这些是菜单项。期望当用户从下拉菜单中选择某个选项时会发生某些事情。它没有当前值的概念。如果您想要一个类似表单的元素,让用户选择一个选项然后继续操作,您可能需要看一下<Input>。 - noveyak
我注意到一个奇怪的问题。 <DropdownButton bsStyle="primary" title={this.state.value} onSelect={this.handleSelect}> 然后,在 handleSelect 中,我写了 this.setState({value: index});console.log(this.state.value); 当我读取控制台输出时,值似乎落后了。也就是说,当我第一次选择一个项目时。控制台会输出状态变量的默认值。如果我选择另一个项目,则控制台将输出我先前选择的值。你知道这是为什么吗? - Cheng
2
setState在React中不是同步操作(来自文档)setState()不会立即改变this.state,而是创建一个挂起的状态转换。在调用此方法后访问this.state可能会潜在地返回现有值。 没有同步操作的保证,调用setState的调用可能会被批处理以获得性能提升。如果您需要在之后执行某些操作,请将回调作为setstate的第二个参数传递。 - noveyak
3
不要篡改这个问题,但是这对我没有用,当我尝试记录evt时,我得到了SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: ".0.2.0.1.0.0.0.0.1.$=11:0.$=11:0.0", nativeEvent: MouseEvent, type: "click", target: a…} - user3196599
1
我正在使用 eventKey.target.innerHTML。不确定这是否是正确的方法,但它能完成工作。 - Nihal Harish
显示剩余3条评论

4

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

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

2
实际上,情况恰恰相反... 函数应该是 handleSelect: function (evtKey, event) {.... - Ehmad Zubair
正确的签名应该是 (eventKey: any, event: Object) => any - Fahad Javed

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
}

要设置默认值,您需要在DropdownButton上使用title属性。
参考:https://react-bootstrap.github.io/components/dropdowns/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接