如何在 react-bootstrap select FromControl 中获取 selected 选项的值

How to get value of selected option in react-bootstrap select FromControl

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

这是我的下拉菜单:

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

you need to bind your function like this ..

 onChange={this.handleCatChange.bind(this)}



    constructor () {
        super();
        this.state = { 
          storeType: '' 
        };
      }


    handleCatChange(e) {
    const type = e.target.value;
        this.setState({
            storeType:type 
        });

    }

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

根据the docs

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

如果您需要确保调用 setState 后事件的顺序,您可以传递一个回调函数。

this.handleCatChange

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