在单选按钮中使用布尔数据的正确方法是什么。如果直接使用,这些值将从布尔值转换为字符串。
预加载的输入字段的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
转换为布尔值,但它感觉有点hackery。另外,仅使用'e.target.checked'将不起作用,因为在某些单选按钮组中,我有其他值而不是布尔值(需要通过)。
一些通用且干净的解决方案是使用从REST转换为REST的常量值表。
有没有特殊的ReactJS方法呢?也许不是。
答案 0 :(得分:5)
目前解决方案是在保存之前将传递的属性从字符串值转换为布尔值。
var function = str2bool(value) {
if (value && typeof value === 'string') {
if (value.toLowerCase() === "true") return true;
if (value.toLowerCase() === "false") return false;
}
return value;
}
并致电转换:
onRadioChange: function(e) {
console.log(str2bool(e.target.value));
// Here we can send the data to further processing (Action/Store/Rest)
}
通过这种方式,数据可以通过操作发送到Rest或Stores,并且可以直接使用单选按钮。
答案 1 :(得分:5)
使用输入的checked属性进行单选按钮。该属性使用布尔值。
答案 2 :(得分:2)
如果您正在寻找使用React管理单选按钮检查状态的方法,这里有一个示例:
var RadioButtons = React.createClass({
getInitialState: function () {
// Assuming there is always one option set to true.
return {
question: this.props.options.filter(function (option) {
return option.value;
})[0].name
};
},
onRadioChange: function (e) {
this.setState({
question: e.target.value
});
},
render: function () {
var options = this.props.options.map(function (option, key) {
return (
<li key={key}>
<input type="radio"
name="question"
onChange={this.onRadioChange}
checked={this.state.question === option.name}
value={option.name} /> {option.name}
</li>
);
}, this);
return (
<ul style={{listStyle: 'none'}}>
{options}
</ul>
);
}
});
然后可以使用此组件将question
列表作为属性传递:
<RadioButtons options={question} />
选中fiddle。
答案 3 :(得分:-1)
对我来说(使用PHP后端),解决方案是将值从true
和false
更改为1
和0
。
我猜PHP将"1"
和"0"
视为布尔值,而将"true"
和"false"
视为字符串。