react实现复选框全选和反选组件

react实现复选框全选和反选组件效果

运行效果图如下:

 

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
// import Menu from '../menu/Menu.jsx';
class List extends Component {
  constructor () {
    super();
    this.state = {
      title: '我是List的标题',
      content: '我是内容部分部分',
      chooseAll: false, // 全选标志
      inters: ['bsball', 'ymball', 'fbball'], // 页面加载默认选中项
      intersAll: ['bsball', 'ymball', 'ppball', 'fbball'],
      fchoose: false // 正反选标志
    };
  }
  // 全选
  chooseAll (event) {
    let {checked, value} = event.target;
    let chooseAll = this.state.inters.length === 4 ? true : false;
    let inters = ['bsball', 'ymball', 'ppball', 'fbball'];
    checked ? (
      this.setState({
        inters,
        chooseAll: checked
      })
    ) : (
      this.setState({
        inters: [],
        chooseAll: checked
      })
    );
  }
  // 点击复选框
  chooseInter (event) {
    let val = event.target.value;
    let checked = event.target.checked;
    let {inters} = this.state;
    // event.stopPropagation();
    // 选中复选框并且值不在数组里面
    if (checked && !this.state.inters.includes(val)) {
      inters.push(val);
    } else {
      // 取消选中的选项
      inters = inters.filter(v => val !== v);
    }
    let chooseAll = inters.length === 4 ? true : false;
    console.log(inters);
    this.setState({
      inters,
      chooseAll
    });
  }
  // 反选处理
  fchooseHandle (event) {
    let {checked, value} = event.target;
    let {inters, intersAll} = this.state;
    let chooseAll = this.state.inters.length === 4 ? true : false;
    let arr = []; // 反选结果
    this.setState({
      fchoose: checked,
      chooseAll
    });
    intersAll.forEach(item => {
      if (!inters.includes(item)) {
        arr.push(item);
      }
    });
    this.setState({
      inters: arr
    });
  }
  componentWillMount () {
    let chooseAll = this.state.inters.length === 4 ? true : false;
    this.setState({
      chooseAll
    });
  }
  render () {
    return (
      
{/* */}

{this.state.title}

{this.state.content}

); } } export default withRouter(List);

 

你可能感兴趣的:(React)