简体   繁体   中英

change selected value dropdown reactjs

I'm using a dropdown box with ReactJS and I'm using the default values that I get from "this.state.whoIsChecked.allowDestroyAll". But when I use it as default value, I can't change the value anymore. Here follows the code I'm using:

<select 
className="form-control" 
id="ada" 
value={this.state.whoIsChecked.allowDestroyAll}>
    <option>true</option>
    <option>false</option>
</select>

You need to add an onChange event with the controlled input and update the state in order to change the value after providing a value to Option field like

handleChange(e) {
     var whoIsChecked = {...this.state.whoIsChecked}
     whoIsChecked.allowDestroyAll = e.target.value
     this.setState({whoIsChecked})
}


render( ) {
 return <select 
    className="form-control" 
    id="ada" 
    onChange={(e) => this.handleChange(e)}
    value={this.state.whoIsChecked.allowDestroyAll}>
        <option value="true">true</option>
        <option value="false">false</option>
    </select>
}

 class App extends React.Component { state= { whoIsChecked: { allowDestroyAll: "true" } } handleChange(e) { var whoIsChecked = {...this.state.whoIsChecked} whoIsChecked.allowDestroyAll = e.target.value this.setState({whoIsChecked}, ()=> {console.log(this.state)}) } render( ) { return <select className="form-control" id="ada" onChange={(e) => this.handleChange(e)} value={this.state.whoIsChecked.allowDestroyAll}> <option value="true">true</option> <option value="false">false</option> </select> } } ReactDOM.render(<App/>, document.getElementById('app')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

You are using the controlled element , using the value property (means controlling the value of selectfield by the state variable), you need to define the onchange method to update that state value otherwise selectfield will become read-only .

Write it like this:

<select 
    className="form-control" 
    id="ada" 
    value={this.state.whoIsChecked.allowDestroyAll}
    onChange={this.change}
>
    <option value='true'>true</option>
    <option value='false'>false</option>
</select>

change = (e) => {
    let whoIsChecked = Object.assign({}, this.state.whoIsChecked)
    whoIsChecked.allowDestroyAll = e.target.value;
    this.setState({whoIsChecked});
}

Note: You need to assign the unique value to each option .

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