鍍金池/ 問答/HTML/ 求一個react全選,反選的例子

求一個react全選,反選的例子

頁面上一個列表,有全選,反選功能,用antd上Checkbox.Group,map遍歷展示就會有問題,把返回來的數(shù)據(jù)某個字段push到plainOptions也是不行,如果不用antd這個,怎么實(shí)現(xiàn)一個全選反選功能呢圖片描述

回答
編輯回答
陪她鬧
2017年9月22日 23:27
編輯回答
故林

你的map展示會有什么問題?

2018年3月27日 06:34
編輯回答
厭遇
 */
import React, {Component} from 'react'
import { observer } from "mobx-react"
import {Checkbox} from 'antd'
const Options = [{id:1,name:'Apple'}, {id:2,name:'Pear'}, {id:3,name:'Orange'}];
@observer
export default class CheckAll extends Component {
    state = {
        Options: [
            {id: 1, name: 'Apple', checked: false},
            {id: 2, name: 'Pear', checked: false},
            {
                id: 3,
                name: 'Orange',
                checked: false
            }],
        checked: false,
        checkedId: []
    };

    onChange=(item)=>{
        let i=0;
        let l=0;
        Options.map((option,index)=>{
            if(option.id==item.id){
                option.checked=!item.checked
            }if(option.checked==true){
                i+=1
            }if(option.checked==false){
                l+=1
            }
        });

        if(Options.length==i){
            this.state.checked=true;
        }if(Options.length==l){
            this.state.checked=false;
        }
        this.setState({
            Options:Options,
            checked:this.state.checked
        })
    }

    handleCheckAll=()=>{
        
        this.setState({checked:!this.state.checked});
        if(!this.state.checked){
            this.state.checkedId=[]
            Options.map((option,index)=>{

                this.state.checkedId.push(option.id)
            })
            this.state.checkedId.map((id,index)=>{
                Options.map((Option,idx)=>{
                    if(Option.id==id){
                        Option.checked=true;
                    }
                })
            })

        }else{
            this.state.checkedId.map((id,index)=>{
                Options.map((Option,idx)=>{
                    if(Option.id==id){
                        Option.checked=false;
                    }
                })
            })
            this.state.checkedId=[]
        }
        this.setState({
            Options:Options
        })
    };
    render(){
        return(
            <div>
                <Checkbox checked={this.state.checked} onClick={this.handleCheckAll.bind(this)}/>全選
                {Options.map((option,index)=>{
                    return(<Checkbox content={option.id} onChange={this.onChange.bind(this,option)} checked={option.checked}>{option.name}</Checkbox>)
                })}

            </div>
        )
    }
}
2018年9月16日 18:11