You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中radio单选框默认选中及点击切换异常问题求助

问题根因

你当前实现的是受控单选框组件,但没有绑定onChange事件更新状态:

  • 对应countryToVisit的单选框硬写了checked属性,没有和状态做动态绑定
  • 点击单选框时没有触发状态更新,React每次重渲染都会按照当前state.countryToVisit的值重新设置选中状态,所以会自动跳回原来的选项,第一次点击实际没有生效,才会出现需要点击两次的问题

修复代码

class App extends Component {
  constructor(props) {
    super(props);
    this.state={
      countries: ['USA', 'UK', 'China', 'Japan', 'Canada'],
      countryToVisit: 'Japan'
    }
    // 绑定事件处理函数this指向
    this.handleRadioChange = this.handleRadioChange.bind(this)
  }

  // 新增单选框变更处理函数
  handleRadioChange(e) {
    this.setState({
      countryToVisit: e.target.id
    })
  }

  render() {
    return (
      <>
        <h1>Where do you want to travel?</h1>
        {this.state.countries.map((country, index)=>{
          return(
            <React.Fragment key={index}>
              <input 
                type='radio' 
                name='test' 
                id={country} 
                // 动态绑定checked属性
                checked={this.state.countryToVisit === country}
                // 绑定变更事件
                onChange={this.handleRadioChange}
              />
              <label htmlFor={country}>{ country }</label>
            </React.Fragment>
          )
        })}
      </>
    )
  }
}

核心修改点

  • 新增了handleRadioChange事件处理函数,点击单选框时会更新state.countryToVisit的值
  • 去掉了冗余的if/else判断,直接通过checked={this.state.countryToVisit === country}动态绑定选中状态
  • 给列表渲染的元素添加了key属性,符合React列表渲染规范,避免潜在的渲染异常
  • 提前绑定了事件处理函数的this指向,确保setState能正常调用

内容的提问来源于stack exchange,提问作者asem shaat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:09:03