Javascript “更改选定值”下拉列表

Javascript “更改选定值”下拉列表,javascript,html,reactjs,Javascript,Html,Reactjs,我在ReactJS中使用了一个下拉框,并且使用了从“this.state.whoIsChecked.allowDestroyAll”中获得的默认值。但当我使用它作为默认值时,我无法再更改该值。下面是我使用的代码: <select className="form-control" id="ada" value={this.state.whoIsChecked.allowDestroyAll}> <option>true</option> &

我在ReactJS中使用了一个下拉框,并且使用了从“this.state.whoIsChecked.allowDestroyAll”中获得的默认值。但当我使用它作为默认值时,我无法再更改该值。下面是我使用的代码:

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

符合事实的
错误的

您需要使用
受控输入添加
onChange
事件,并更新状态,以便在向选项字段提供值后更改值,如

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>
}
handleChange(e){
var whoIsChecked={…this.state.whoIsChecked}
whoIsChecked.allowDestroyAll=e.target.value
this.setState({whoIsChecked})
}
渲染(){
返回此.handleChange(e)}
值={this.state.whoIsChecked.allowDestroyAll}>
符合事实的
错误的
}
类应用程序扩展了React.Component{
状态={
被检查者:{
allowDestroyAll:“正确”
}
}
手变(e){
var whoIsChecked={…this.state.whoIsChecked}
whoIsChecked.allowDestroyAll=e.target.value
this.setState({whoIsChecked},()=>{console.log(this.state)})
}
渲染(){
返回此.handleChange(e)}
值={this.state.whoIsChecked.allowDestroyAll}>
符合事实的
错误的
}
}
ReactDOM.render(,document.getElementById('app'))

您正在使用,使用value属性(意味着通过
state
变量控制
selectfield
的值),您需要定义
onchange
方法来更新该
状态
值,否则
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});
}

符合事实的
错误的
变化=(e)=>{
让whoIsChecked=Object.assign({},this.state.whoIsChecked)
whoIsChecked.allowDestroyAll=e.target.value;
this.setState({whoIsChecked});
}

注意:您需要为每个
选项指定唯一的值

这是非常模糊的。请尝试提供更多上下文。这已在其他线程上得到回答。请查看可能的副本,请查看上面看似重复的问题,如果你相信这不是一个重复,然后添加更多的细节,你的帖子概述你的问题和你尝试过的,没有奏效。考虑接受和投票的答案,如果它帮助