更改选定值下拉列表反应

时间:2017-06-06 18:44:58

标签: javascript html reactjs

我使用ReactJS的下拉框,并使用我从" this.state.whoIsChecked.allowDestroyAll"中获得的默认值。但是当我将它用作默认值时,我无法再更改该值。以下是代码I' m使用:

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

2 个答案:

答案 0 :(得分:1)

您需要使用onChange添加controlled input事件并更新状态,以便在向Option字段提供值后更改值,例如

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>

答案 1 :(得分:1)

您正在使用controlled element,使用value属性(意味着通过selectfield变量控制state的值),您需要将onchange方法定义为更新state值,否则selectfield将变为只读

像这样写:

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

注意:您需要为每个option分配唯一值。