react实现复选框全选和反选组件效果
时间:2021-01-13 09:50:18|栏目:JavaScript代码|点击: 次
本文实例为大家分享了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);
上一篇:js日期对象兼容性的处理方法
栏 目:JavaScript代码
本文标题:react实现复选框全选和反选组件效果
本文地址:http://www.codeinn.net/misctech/44415.html