react复选框全选和反选组件 react实现复选框全选和反选组件效果
#麻辣小龙虾# 人气:0想了解react实现复选框全选和反选组件效果的相关内容吗,#麻辣小龙虾#在本文为您仔细讲解react复选框全选和反选组件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:react复选框全选,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 /> */} <h1>{this.state.title}</h1> <p>{this.state.content}</p> <p> <label> <input type="checkbox" value="bsball" checked={this.state.fchoose} onClick={this.fchooseHandle.bind(this)}/>{this.state.fchoose ? '取消反选' : '反选'} </label> <label> <input type="checkbox" value="bsball" checked={this.state.chooseAll} onClick={this.chooseAll.bind(this)}/>{this.state.chooseAll ? '取消全选' : '全选'} </label> </p> <p> <label> <input type="checkbox" value="bsball" checked={this.state.inters.includes('bsball')} onClick={this.chooseInter.bind(this)}/>篮球 </label> <label> <input type="checkbox" value="ymball" checked={this.state.inters.includes('ymball')} onClick={this.chooseInter.bind(this)}/>羽毛球 </label> <label> <input type="checkbox" value="ppball" checked={this.state.inters.includes('ppball')} onClick={this.chooseInter.bind(this)}/>兵乓球 </label> <label> <input type="checkbox" value="fbball" checked={this.state.inters.includes('fbball')} onClick={this.chooseInter.bind(this)}/>足球 </label> </p> </div> ); } } export default withRouter(List);
加载全部内容