我想问一下,场景是这样的。我有多个复选框,但我的问题是每当我勾选一个复选框时,所有 4 个复选框都会被选中。还有为什么复选框的值只是 true 或 false。这是我的复选框:
<div className="checkbox">
<label><Field name="investor_stage" component="input" type="checkbox" value="Seed" /> Seed</label>
</div>
<div className="checkbox">
<label><Field name="investor_stage" component="input" type="checkbox" value="Early Stages" /> Early Stages</label>
</div>
<div className="checkbox">
<label><Field name="investor_stage" component="input" type="checkbox" value="Formative Stages" /> Formative Stages</label>
</div>
<div className="checkbox">
<label><Field name="investor_stage" component="input" type="checkbox" value=" Later Stages" /> Later Stages</label>
</div>
对于像我这样刚接触 redux 和 React 的人可能会发现提到的原始代码here https://github.com/erikras/redux-form/issues/1037#issuecomment-243003954令人困惑。我修改并将其转换为 ES6 类。我还删除了引导程序、验证并使其易于调试。
这是修改后的代码
import React from 'react';
class CheckboxGroup extends React.Component {
checkboxGroup() {
let {label, required, options, input, meta} = this.props;
return options.map((option, index) => {
return (
<div className="checkbox" key={index}>
<label>
<input type="checkbox"
name={`${input.name}[${index}]`}
value={option.name}
checked={input.value.indexOf(option.name) !== -1}
onChange={(event) => {
const newValue = [...input.value];
if (event.target.checked) {
newValue.push(option.name);
} else {
newValue.splice(newValue.indexOf(option.name), 1);
}
return input.onChange(newValue);
}}/>
{option.name}
</label>
</div>)
});
}
render() {
return (
<div>
{this.checkboxGroup()}
</div>
)
}
}
export default CheckboxGroup;
Usage:
let optionsList = [{id: 1, name: 'Optoin1'}, {id: 2, name: 'Option 2'}, {id: 3, name: 'Option 3'}]
<Field name="roles" component={CheckboxGroup} options={optionsList} />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)