我使用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>
答案 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
分配唯一值。