[英]How can I preserve a checkbox value type in React?
我正在jsx / react中工作,我想保留复选框的值类型。
<input
type="checkbox"
name={name}
value={value}
checked={checked}
disabled={disabled}
onChange={this.handleChange}
/>
目前,如果该值是例如布尔值或数字,则将其转换为onChange处理程序的e.target.value句柄中的字符串。 例如'false'或'1'。
有没有一种方法可以保留类型,或者有比JSON.parse(JSON.stringify())
更多的惯用方法来重建类型?
您好开发人员检查此保留值复选框
<Col sm={6}>
<FormGroup check inline>
<CustomInput type="radio" id="IsPaymentKind" label="Payment Kind"
value="Payment Kind"
checked={this.state.voucher_kind === 'Payment Kind'}
onChange={event => {
this.setState({ voucher_kind: event.target.value });
}}
/>
</FormGroup>
<FormGroup check inline>
<CustomInput type="radio" id="IsReceiptKind" label="Receipt Kind"
value="Receipt Kind"
checked={this.state.voucher_kind === 'Receipt Kind'}
onChange={event => {
this.setState({ voucher_kind: event.target.value });
}} />
</FormGroup>
<FormGroup check inline>
<CustomInput type="radio" id="Other" label="Other"
value="Other" checked={this.state.voucher_kind === 'Other'}
onChange={event => {
this.setState({ voucher_kind: event.target.value });
}} />
</FormGroup>
</Col>
HTML复选框值(与所有属性一样)必须是文本。 这意味着所有非字符串数据都必须序列化为字符串。 默认情况下,React使用.toString()。
我可以得出结论,最灵活,可逆和惯用的方法是使用JSON.stringify()
然后使用JSON.parse()
进行恢复。
<input
type="checkbox"
name={name}
value={JSON.stringify(value)}
checked={checked}
disabled={disabled}
onChange={this.handleChange}
/>
handleChange(e) {
const value = JSON.parse(e.target.value)
}
如果只需要布尔值和数字值,则使用Fred的(未经编辑的原始格式)选项。
<input
type="checkbox"
name={name}
value={value}
data-type={typeof value}
checked={checked}
disabled={disabled}
onChange={this.handleChange}
/>
handleChange(e) {
const type = e.target.getAttribute('data-type'))
const { value: stringValue } = e.target
switch(type) {
case 'number': {
}
case 'boolean': {
}
default: {
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.