简体   繁体   中英

onchange event on react select trigger only by clicking

i have an <select> in my react app

<select onChange={ e=>{this.setState({selectedValue:e.target.value})} }>
    {this.state.someArr.map( val => <option value={val}> something </option>) }
</select>

now if someArr in the state changes , it cause the new options rendered inside select element
but onchange not triggered and selectedValue inside the state remains untouched
how can i overcome this issue? i want new value to set automatically

HERE IS JSBIN

First of all, when using React you should never pass an arrow function because it passes different instance each time and can cause unnecessary rendering.

The reason it doesnt work, is because you're trying to access the event in the setState function and you cant do that.

Here is what you should do:

export default class Component extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            selectedValue: '',
            someArr: []
        };
    }

    onChange(e) {
        let value = e.target.value;
        this.setState({ selectedValue: value });
    }

    render () {
        return <select onChange={this.onChange}}>
                {this.state.someArr.map( val => <option value={val}> something </option>) }
            </select>   
    }
}

All you need to do is set the value prop properly.

<select value={this.state.selectedValue} onChange={ e=>{this.setState({selectedValue:e.target.value})} }>
    {this.state.someArr.map( val => <option value={val}> something </option>) }
</select>

I hope this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM