单击另一个单选按钮后,“已选中”单选按钮消失

时间:2019-09-07 08:53:05

标签: reactjs bootstrap-4

我有两个单选按钮,其中一个被“选中”(根据服务器响应-0或10),我需要单击其中一个按钮将新数据发送到服务器(以太值0或10) 。我有工作代码,数据正确发送到服务器,一切正常。但是问题是-单击两个按钮后,两个按钮中的“已选中”属性都消失了。

有人可以帮我吗?

this.state = {          
   status: ""          
}


statusHandler(e) {
  this.setState({ status: e.target.value });
}

<div className="modal-body">
  <div className="form-check form-check-inline">
    <input className="form-check-input"
      type="radio"
      name="inlineRadioOptions"
      id="inlineRadio1"
      value={0}
      checked={this.state.status === 0 ? true : false}
      onChange={(e) => this.statusHandler(e)} />
    <label className="form-check-label" htmlFor="inlineRadio1">Open</label>
  </div>
  <div className="form-check form-check-inline">
    <input className="form-check-input"
      type="radio"
      name="inlineRadioOptions"
      id="inlineRadio2"
      value={10}
      checked={this.state.status === 10 ? true : false}
      onChange={(e) => this.statusHandler(e)} />
    <label className="form-check-label" htmlFor="inlineRadio2">Done</label>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

原因是e.target.value为您提供了'String'的价值,而您正在使用===检查条件。因此,您需要将值转换为Number,也可以使用==检查条件。

您可以使用string to number+e.target.valueparseInt进行转换。

请参见下面的代码段和有效的stackblitz演示。

class App extends Component {
  constructor() {
    this.state = {
      status: ''
    };
  }
  statusHandler(e) {
    this.setState({ status: +e.target.value });
  }

  render() {
    return (
      <div className="modal-body">
        <div className="form-check form-check-inline">
          <input className="form-check-input"
            type="radio"
            name="inlineRadioOptions"
            id="inlineRadio1"
            value={0}
            checked={this.state.status === 0 ? true : false}
            onChange={(e) => this.statusHandler(e)} />
          <label className="form-check-label" htmlFor="inlineRadio1">Open</label>
        </div>
        <div className="form-check form-check-inline">
          <input className="form-check-input"
            type="radio"
            name="inlineRadioOptions"
            id="inlineRadio2"
            value={10}
            checked={this.state.status === 10 ? true : false}
            onChange={(e) => this.statusHandler(e)} />
          <label className="form-check-label" htmlFor="inlineRadio2">Done</label>
        </div>
      </div>
    );
  }
}
相关问题