react實現複選框全選和反選元件效果
阿新 • • 發佈:2020-08-26
本文例項為大家分享了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','ppball',fchoose: false // 正反選標誌 }; } // 全選 chooseAll (event) { let {checked,value} = event.target; let chooseAll = this.state.inters.length === 4 ? true : false; let inters = ['bsball','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);
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。