我有两个单选按钮,其中一个被“选中”(根据服务器响应-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>
答案 0 :(得分:1)
原因是e.target.value
为您提供了'String'的价值,而您正在使用===
检查条件。因此,您需要将值转换为Number
,也可以使用==
检查条件。
您可以使用string to number或+e.target.value
来parseInt
进行转换。
请参见下面的代码段和有效的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>
);
}
}