gpt4 book ai didi

javascript - 为什么输入值中设置的值只是字符串类型?

转载 作者:行者123 更新时间:2023-11-30 11:06:51 24 4
gpt4 key购买 nike

这里我想在我的 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 来设置它。但随后它变得不受控制,这是不鼓励的。

最佳答案

而不是将值设置为字符串

<input type="radio" value="1" />

设置为整数

<input type="radio" value={1} />

如果您希望状态的某些值严格为数字,也请尝试使用 === 进行比较,否则您的比较将不会非常严格

编辑

要选中单选按钮,您可以通过将其与状态值进行比较来设置单选按钮的 checked 属性

<input type="radio" checked={this.state.frequency === 1} value={1} />

关于javascript - 为什么输入值中设置的值只是字符串类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55255042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com