在单选按钮中使用布尔数据的正确方法是什么。如果直接使用,这些值将从布尔值转换为字符串。
预加载的输入字段的 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 方法可以做到吗?也许不吧。
原文由 Pekka 发布,翻译遵循 CC BY-SA 4.0 许可协议
目前的解决方案是在保存之前将传递的属性从字符串值转换为布尔值。
并调用转换:
这样,数据就可以通过操作发送到 Rest 或 Stores,并且可以直接与单选按钮一起使用。