React实现checkbox的反选和全选

这个其实还挺适合入门react练手的,今天看到网上有这个例子但是写的实在不是很好,我复写了一下,感觉还不错,发上来参考一下咯

class Checkboxcomponent extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            chooseList : ['apple','lemon','melon','orange'],
            chooseCheck : 0,
            Allchoose : false,
            reverseCheck : false,
            isAuto : false
        }
    }
    Allchoose(e){
        if(this.state.Allchoose){
            this.setState({
                chooseCheck : 0,
                Allchoose : false,
                isAuto : false,
            })
        }else{
            this.setState({
                Allchoose : true,
                chooseCheck : this.state.chooseList.length,
                isAuto : false,
            });
        }
    }
    checkAllChoose(ItemChecked){
        if(this.state.isAuto = true)this.state.isAuto = false;
        ItemChecked ? this.state.chooseCheck++ : this.state.chooseCheck--;
        console.log(this.state.chooseCheck);
        if(this.state.chooseCheck == this.state.chooseList.length){
            this.setState({
                Allchoose : true,
                isAuto : true
            })
        }else{
            if(this.state.Allchoose == true){
                this.setState({
                    Allchoose : false,
                    isAuto : true
                });
            }
        }
    }
    Reversechoose(e){
        let newNum = this.state.chooseList.length - this.state.chooseCheck;
        if(newNum == this.state.chooseList.length){
            this.setState({
                Allchoose : true,
                isAuto : true
            })
        }else{
            this.setState({
                Allchoose : false,
                isAuto : true
            })
        }
        this.setState({
            reverseCheck : !this.state.reverseCheck,
            chooseCheck : this.state.chooseList.length - this.state.chooseCheck
        });
    }
    render(){
        return (
            
全选 {this.Allchoose(e)}} checked = {this.state.Allchoose} /> 反选 {this.Reversechoose(e)}} checked = {this.state.reverseCheck}/> { this.state.chooseList.map((item,idx)=>{ return (
{item} {this.checkAllChoose(ItemChecked)}} Allchoose = {this.state.Allchoose} Reverse = {this.state.reverseCheck} isAuto = {this.state.isAuto}/>
) }) }
) } } class CheckboxItemcomponent extends React.Component{ constructor(props){ super(props); this.state = { checked : false, } } _clickHandle(e){ this.props.checkAllChoose(!this.state.checked); this.setState({ checked : this.state.checked ? false : true }); } componentWillReceiveProps(nextprops){ console.log(nextprops.isAuto); if(nextprops.isAuto == false)this.state.checked = nextprops.Allchoose; if(nextprops.Reverse != this.props.Reverse){ this.setState({ checked : !this.state.checked }) } } render(){ return ( {this._clickHandle(e)}} /> ) } }

刚想睡觉结果发现有bug。。新加上一个判断值解决了,这个逻辑有点要人亲命。。难廋

有什么问题请评论区指正噢

你可能感兴趣的:(前端,react)