【问题标题】:React-bootstrap how to capture the value of dropdown listReact-bootstrap 如何捕获下拉列表的值
【发布时间】:2015-10-09 04:33:49
【问题描述】:

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


    【解决方案1】:

    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 属性中的任何内容。如果你想处理一个默认值,你可以在值为null时设置一个值。

    【讨论】:

    • 太棒了,谢谢!让我澄清我的第二个问题。我的下拉列表中有三个选项。我希望默认选择第一个选项。实现此目的的正确方法是什么?再次感谢!哦,还有,你在哪里找到关于 eventKey 的文档?我确实浏览了 react-bootstrap 的网站,但找不到它......
    • 嗯,我认为问题在于这些是菜单项。期望是当用户从下拉列表中选择某些内容时应该会发生某些事情。它没有当前值的概念。如果您尝试使用类似元素的表单,用户可以在其中选择一个选项然后继续,您可能需要查看
    • setState 不是 react 中的同步操作(来自文档) setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。在调用此方法后访问 this.state 可能会返回现有值。无法保证对 setState 的调用的同步操作,并且可能会批处理调用以提高性能。如果你之后需要做一些事情,传递一个回调作为 setstate 的第二个参数。
    • 不要劫持这个问题,但这对我不起作用,我在尝试记录 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…}
    • 我正在使用 eventKey.target.innerHTML。不确定这是否是正确的方法,但它确实有效
    【解决方案2】:

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

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

    【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      要设置默认值,您需要在DropdownButton 上使用title 属性

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

      【讨论】:

        猜你喜欢
        • 2021-11-26
        • 1970-01-01
        • 2019-08-13
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多