最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React radio button not update selection - Stack Overflow

programmeradmin1浏览0评论

Trying React radio but the strange thing is that the radio selection will not update its view. Can anyone take a look at the code below and let me know what's wrong?

  class Test extends React.Component {
    constructor(props){
    super(props);

    this.state = {
      radioVal: "first"
    }
  }

  handleRadioSelection(e){
    e.preventDefault();

    this.setState({
      radioVal:e.target.value
    })
  }

    render(){
      return (
        <div>
            <label>
            <input type="radio" onChange={this.handleRadioSelection.bind(this)} 
            checked={ this.state.radioVal==="first"} 
            value="first" 
            name="radio1" /> 1 <br />
          </label>

          <label>
            <input type="radio" onChange={this.handleRadioSelection.bind(this)} 
            checked={this.state.radioVal==="second"} 
            value="second" 
            name="radio1" /> 2 <br />
          </label>
            { "Selected: " } {this.state.radioVal}
        </div>
    )
  }
}

React.render(<Test />, document.getElementById('container'));

Trying React radio but the strange thing is that the radio selection will not update its view. Can anyone take a look at the code below and let me know what's wrong?

  class Test extends React.Component {
    constructor(props){
    super(props);

    this.state = {
      radioVal: "first"
    }
  }

  handleRadioSelection(e){
    e.preventDefault();

    this.setState({
      radioVal:e.target.value
    })
  }

    render(){
      return (
        <div>
            <label>
            <input type="radio" onChange={this.handleRadioSelection.bind(this)} 
            checked={ this.state.radioVal==="first"} 
            value="first" 
            name="radio1" /> 1 <br />
          </label>

          <label>
            <input type="radio" onChange={this.handleRadioSelection.bind(this)} 
            checked={this.state.radioVal==="second"} 
            value="second" 
            name="radio1" /> 2 <br />
          </label>
            { "Selected: " } {this.state.radioVal}
        </div>
    )
  }
}

React.render(<Test />, document.getElementById('container'));
Share Improve this question edited Jul 1, 2022 at 19:43 Jonas 129k103 gold badges328 silver badges405 bronze badges asked Apr 15, 2017 at 18:54 max limax li 2,4674 gold badges31 silver badges46 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Remove e.preventDefault(); from handleRadioSelection. Is there a reason why you added that line in the first place?

发布评论

评论列表(0)

  1. 暂无评论