在这里,我想在我的reactjs组件中将setstate中的值设置为整数。 我无法执行此操作,因为该值未设置为整数,因此在单选按钮中未将其选中。
constructor(props) {
super(props);
this.state = {
frequency: 1,
}
handleSelectChange(event) {
this.setState({
frequency: event.target.value
})
};
<div className = "custom-control custom-radio custom-control-inline"
onChange = {
this.handleSelectChange.bind(this)
} >
<
input type = "radio"
id = "oneTime"
value = "0"
name = "type"
onChange = {
event => this.handleSelectChange(event)
}
checked = {
this.state.frequency === "0"
}
className = "custom-control-input" / >
<
label className = "custom-control-label"
htmlFor = "oneTime" > {
Labels.PRODUCT_SUBSCRIPTION.ONETIME
} <
/label> < /
div > <
div className = "custom-control custom-radio custom-control-inline" >
<
input type = "radio"
id = "continuous"
value = "1"
name = "type"
checked = {
this.state.frequency === "1"
}
onChange = {
event => this.handleSelectChange(event)
}
className = "custom-control-input" / >
<
label className = "custom-control-label"
htmlFor = "continuous" > {
Labels.PRODUCT_SUBSCRIPTION.CONTINUOUS
}
</label>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
我知道我们可以使用defaultValue进行设置。但是后来变得不受控制,这是不鼓励的。
答案 0 :(得分:3)
而不是像字符串一样设置值
<input type="radio" value="1" />
将其设置为整数
<input type="radio" value={1} />
如果您希望状态的某些值严格地为数字,也可以尝试在比较时使用===
,否则您的比较就不会很严格
修改
要选中单选按钮,然后可以通过将其与状态值进行比较来设置单选的checked
属性
<input type="radio" checked={this.state.frequency === 1} value={1} />
答案 1 :(得分:0)
您应该将值初始化为:
<input type="radio"
checked={this.state.frequency === 1}
value={this.state.frequency || 0} />
您已经从另一个答案中注意到,value="0"
将代表字符串0
,而value={0}
将代表整数0
。