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

烂漫一生 提交于 2019-12-24 06:08:12

问题


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

Here is my dropdown menu:

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

回答1:


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.

According to 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.

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

this.handleCatChange

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



回答2:


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

    }


来源:https://stackoverflow.com/questions/45612278/how-to-get-value-of-selected-option-in-react-bootstrap-select-fromcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!