簡體   English   中英

如何組織多個復選框?

[英]How to organize multiple checkboxes?

我想組織多個復選框。 我決定將選擇框的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渲染它並拋出控制台:

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.

我之所以這樣理解,是因為我正在使用用於檢查屬性的方法。 如何做同樣的事情而不會收到警告?

您的輸入類型需要為復選框,而不是單選。 您還需要使用您checked屬性來引用狀態。

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

這將根據復選框的狀態將狀態設置為truefalse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM