如何正确地在单选按钮中使用布尔数据。如果直接使用,则这些值将从布尔转换为字符串。
预加载的输入字段的JSON数据:
var question = [
{value: true, name: "Yes"},
{value: false, name: "Not this time"}
]
单选按钮字段:
<input type="radio"
name="question"
onChange={this.state.onRadioChange}
value={this.state.question[0].value} /> {this.state.question[0].name}
<input type="radio"
name="question"
onChange={this.state.onRadioChange}
value={this.state.question[1].value} /> {this.state.question[1].name}
onRadioChange的绑定:
onRadioChange: function(e) {
console.log(e.target.value);
}
控制台日志显示所选值从布尔值转换为字符串。
处理此问题的一种方法是在onRadioChange
函数中添加一个额外的函数,将"true"/"false"
字符串从e.target.value
转换为布尔值,但这种方法有些不正规。另外,仅使用'e.target.checked'不起作用,因为在某些单选按钮组中,我有其他需要传递的非布尔值。
一些通用和干净的解决方案是使用常量值表,该表从REST转换并返回。
是否有特殊的ReactJS方法来解决这个问题?也许没有。
""
,即!""; // true
。 - Paul S.foo || ''
,但是在此之后你可能需要检查提交的数据,因为 false 选择可能会消失。 - Paul S.value
是否表示单选按钮被选中?为什么要将单选按钮的值设置为布尔值? - dreyescat