我想问一下,这是场景。我有多个复选框,但是我的问题是,每当我勾选一个复选框时,都会选中所有4个复选框。还有为什么checkbox的值是true还是false。这是我的checkbox:

<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提到的原始代码令人困惑。我修改并将其转换为ES6类。我还删除了 bootstrap ,验证并使其易于调试。

这是修改后的代码

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;

用法:
let optionsList = [{id: 1, name: 'Optoin1'}, {id: 2, name: 'Option 2'}, {id: 3, name: 'Option 3'}]
<Field name="roles" component={CheckboxGroup} options={optionsList} />

关于reactjs - Redux形式的多个复选框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42836060/

10-09 14:24