首页 > 解决方案 > 单选按钮不允许我切换反应

问题描述

class Actor extends Component {

   constructor(props){ 
      this.handleCheck = this.handleCheck.bind(this);
   }

   state={
      voices : [
         {"Voice":"Indian English Female Voice 1"},
         {"Voice":"Indian English Female Voice 2"},
         {"Voice":"Indian English Male Voice 1"}
      ],
      checkedElement:""
   }

   handleCheck(){
      this.setState({checkedElement:event.target.value})
   }

   render(){
     return(
       {voices.map((item,index)=>{
            return(
                <label key={index} htmlFor = {item.Voice}>
                    {item.Voice}
                    <input
                       key = {index+1} 
                       value={item.Voice} 
                       type = "radio"  
                       onChange ={this.handleCheck}/>
                </label>
            )
        })}
     )
   }
}

这显示为三个选项,但是一旦我选中其中一个,当我切换到下一个选项时,它不会取消选中第一个。它只是保持选中状态,因此不会使其成为唯一的选择。

标签: javascripthtmlreactjs

解决方案


对于上面的代码,你可以添加一个属性'name'来输入,就像

<input 
  name={'item'} 
  key = {index+1} 
  value={item.Voice} 
  type = "radio"  
  onChange ={this.handleCheck}
 />.

您还可以从链接中查看示例。


推荐阅读