FromControl中获取所选选项的值

FromControl中获取所选选项的值

本文介绍了如何在react-bootstrap select FromControl中获取所选选项的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据存储在组件状态中的值将用户从下拉列表中选择的内容写入 firebase 数据库,但我不知道如何获取所选选项的值并将其更新为storeType 状态

I'm trying to write what the user selects from a dropdown to a firebase database based off the value stored in the component state, but I can't figure out how to get the value of the selected option and update it to the storeType state

这是我的下拉菜单:

<FormGroup>
                        <FormControl
                            componentClass="select"
                            placeholder="Store type"
                            onChange={this.handleCatChange}
                        >
                            <option value="placeholder">Choose eatery type...</option>
                            <option value="cafe">Cafe</option>
                            <option value="bakery">Bakery</option>
                            <option value="pizza">Pizza store</option>
                            <option value="sushi">Sushi store</option>
                            <option value="buffet">Buffet</option>
                            <option value="donut">Donut store</option>
                            <option value="other">Other</option>
                        </FormControl>
</FormGroup>

this.handleCatChange:

handleCatChange(e) {
    this.setState({
        storeType: e.target.value
    })
    console.log(this.state.storeType)
}

推荐答案

您的状态有效,但在您执行 console.log 时无效.这是因为 setState 是异步的,不会立即改变你的状态值.

Your state is valid, but not when you do your console.log. It's because setState is asynchronous and does not mutate immediately your state values.

根据文档

setState() 不会立即改变 this.state 而是创建一个待处理的状态转换.调用 this 后访问 this.state方法可能会返回现有值.没有保证调用 setState 和调用的同步操作可能进行批处理以提高性能.

如果在调用 setState 后需要确保事件的顺序,可以传递回调函数.

If you need to ensure ordering of events after a setState call is made, you can pass a callback function.

handleCatChange(e) {
    this.setState({
        storeType: e.target.value
    }, () => console.log(this.state.storeType))
}

这篇关于如何在react-bootstrap select FromControl中获取所选选项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:20