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

编程学习 2021-07-04 14:06www.dzhlxh.cn编程入门
这篇文章主要为大家详细介绍了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 (
  <div className="list">
  {/* <Menu /> * 

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板