简体   繁体   English

如何组织多个复选框?

[英]How to organize multiple checkboxes?

I want to organize multiple checkboxes. 我想组织多个复选框。 I decided to keep an array of ids of chosen boxes in state.And using method want to give them statuses "checked". 我决定将选择框的ID数组保持在state.And,并使用方法将其状态设为“已选中”。

constructor(props) {
        super(props);
        this.state = {
            checkboxes: []
        }
    }

for(let i=0; i<checkboxData.length; i++) {
            checkboxes.push(
                <List.Item key = { checkboxData[i].id }>
                    <div className="ui checkbox">
                        <input type="radio"
                               id={checkboxData[i].id}
                               checked={ ()=>this.getCheckboxStatus(checkboxData[i].id)}
                               onChange = { this.setTag }
                        />
                            <label>{checkboxData[i].name}</label>
                    </div>
                    <List.Content floated="right" >
                        <Label>
                            0
                        </Label>
                    </List.Content>
                </List.Item>
            );
        }

getCheckboxStatus = checkBoxId => {
        let { checkboxes } =this.props;
        console.log('IDS', checkBoxId)
        if (checkboxes.length === 0) {
            return false;
        } else if (checkboxes.indexOf(checkBoxId)!==-1){
            return true;
        }

        return false;

    };

    setTag = e => {
        let { checkboxes } = this.state;
        if ( checkboxes.length === 0 ) {
            checkboxes.push( e.target.id );
        } else {
            if(checkboxes.indexOf(e.target.id)!==-1) {
                checkboxes.splice(checkboxes.indexOf(e.target.id),1);
            } else {
                checkboxes.push( e.target.id );
            }
        }
        this.setState({ checkboxes: checkboxes })
    }

React renders it and throws in console: React渲染它并抛出控制台:

Warning: Invalid value for prop `checked` on <input> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM.

How I understand this is because I'm using method for checked attribute. 我之所以这样理解,是因为我正在使用用于检查属性的方法。 How can I do same thing and not receive warning? 如何做同样的事情而不会收到警告?

Your input type needs to be checkbox, not radio. 您的输入类型需要为复选框,而不是单选。 You also need to reference state with your checked attribute. 您还需要使用您checked属性来引用状态。

 <input 
     type="checkbox"
     id={checkboxData[i].id}
     checked={this.state.checkBoxes[i]}
     onChange={this.setTag}
 />

This will set state with true or false depending on the state of the checkbox 这将根据复选框的状态将状态设置为truefalse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM