ant design的table組件實(shí)現(xiàn)全選功能以及自定義分頁(yè)
我就廢話不多說(shuō)了,大家還是直接看代碼吧~
ant design的table組件實(shí)現(xiàn)全選功能以及自定義分頁(yè)
直接附上全部代碼以及截圖了
import './index.scss'; import React from 'react'; import {Checkbox, Table, Popconfirm} from 'antd'; class TestComponent extends Component { constructor (props) { super(props); this.state = { visible: false, indeterminate: true, checkAll: false, data: this.getData(), pageSize: 10 }; } state = { collapsed: false, mode: 'inline', selectedRowKeys: [], value: undefined, }; onChange = (value) => { console.log(value); this.setState({ value }); }; onSelectChange = (selectedRowKeys) => { console.log('selectedRowKeys changed: ', selectedRowKeys); this.setState({selectedRowKeys}); }; /** * 全選 * @param e */ onCheckAllChange = (e) => { const { data } = this.state; this.setState({ selectedRowKeys: e.target.checked ? data.map((item, index) => index) : [], }); }; getData = () => { const data = []; for (let i = 0; i < 8; i++) { data.push({ id: '00'+i, name: '張三'+i, age: i, address: '重慶市區(qū)...', phone: 247839279, }); } return data; }; /** * 刪除 * @param {object} id */ handleDel = (id) => { this.setState(prevState => ({ data: prevState.data.filter(item => item.id !== id) })); }; /** * 分頁(yè)的改變 */ onShowSizeChange=(current, pageSize)=> { console.log(current, pageSize); this.setState({ pageSize: pageSize, }); } get columns () { const self = this; return [ { title: '學(xué)號(hào)', dataIndex: 'id', align: 'center', key: '1', }, { title: '姓名', dataIndex: 'name', align: 'center', key: '2', }, { title: '年齡', dataIndex: 'age', align: 'center', key: '3', }, { title: '住址', dataIndex: 'address', align: 'center', key: '4', }, { title: '電話', align: 'center', dataIndex: 'phone', key: '5', }, { title: '操作', align: 'center', dataIndex: 'operation', render(text,record) { console.log(111, record); return ( <div align="center"> <a className="edit-data" href="http://localhost:8000/zh/assetDemo/info" rel="external nofollow" >添加</a> <a href="http://localhost:8000/zh/assetDemo/edit" rel="external nofollow" >編輯</a> <Popconfirm title="確定刪除?" onConfirm={() => self.handleDel(record.id)} > <span style={{cursor: 'pointer', color: '#3f87f6'}}>刪除</span> </Popconfirm> </div> ); } } ]; } render() { const {selectedRowKeys} = this.state; const { data } = this.state; const rowSelection = { selectedRowKeys, onChange: this.onSelectChange, hideDefaultSelections: true, onSelection: this.onSelection, }; return ( <div className="right"> <Table columns={this.columns} dataSource={data} rowSelection={rowSelection} pagination={{ simple: false, showSizeChanger: true, showTotal: (count) => { let pageNum = Math.ceil(count / this.state.pageSize); return '共 ' + pageNum + '頁(yè)' + '/' + count + ' 條數(shù)據(jù)'; }, onShowSizeChange: this.onShowSizeChange }} bordered /> <div className=""> <Checkbox indeterminate={this.state.data.length !== this.state.selectedRowKeys.length && this.state.selectedRowKeys.length !== 0} onChange={this.onCheckAllChange} checked={this.state.data.length === this.state.selectedRowKeys.length} >全選 </Checkbox> <span style={{cursor: 'pointer',color: '#3f87f6'}}> 批量刪除 </span> </div> </div> ); } } export default TestComponent;
截圖:
補(bǔ)充知識(shí):ant design pro帶分頁(yè) 自定義表格列 搜索表格組件封裝
ant design pro中有一個(gè)基礎(chǔ)表格的封裝,但是分頁(yè)是前端分頁(yè)處理數(shù)據(jù);
項(xiàng)目中每個(gè)頁(yè)面都有用到表格,且表格都有分頁(yè)、搜索、自定義表格,所以封裝了一個(gè)定制的表格組件
實(shí)現(xiàn)頁(yè)面效果
組件參數(shù)
參數(shù) | 說(shuō)明 | 類(lèi)型 | 默認(rèn)值 |
---|---|---|---|
tablePatam | 表格的一些參數(shù),pageSize/pageNo/loading/filterParam Object {} | ||
data | 表格數(shù)據(jù) | array | [] |
rowKey | 頁(yè)面的唯一key | string | “” |
pathName | 頁(yè)面路徑 | String | “” |
columns | 表格的列數(shù)據(jù) | Array | [] |
changeSearch | 改變搜索內(nèi)容的方法 | function | |
onChange | 表格排序、過(guò)濾、分頁(yè)的方法調(diào)用 | function | |
handleSearch | 處理點(diǎn)擊搜索的方法 | function | |
handleRefresh | 點(diǎn)擊刷新按鈕的方法 | function | |
searchPlaceHolder | 搜索框中的placeholder內(nèi)容 | String | 按名稱(chēng)搜索 |
封裝的注意點(diǎn)
分頁(yè)
排序
搜索
頁(yè)面整個(gè)代碼
組件頁(yè)面
import React, { PureComponent, Fragment } from 'react'; import { connect } from 'dva'; import { Table, Button, Input, Checkbox, Icon, Popover, Col } from 'antd'; import styles from './index.less'; const { Search } = Input; function initColumns(columns) { const lists = columns.map(i => { return { show: true, ...i, }; }); return lists; } function filterColumes(columns) { const filterData = columns.filter(i => !!i.dataIndex); const initColumn = filterData.map(i => { return { dataIndex: i.dataIndex, show: i.show, }; }); return initColumn; } function saveColumns(list, path) { const str = localStorage.getItem(path); let columns = []; if (str) { const storage = JSON.parse(str); list.forEach(item => { const one = storage.find(i => i.dataIndex === item.dataIndex); const obj = { ...item, }; if (one) { obj.show = one.show; } columns.push(obj); }); } else { const simple = filterColumes(list); localStorage.setItem(path, JSON.stringify(simple)); columns = list; } return columns; } @connect(({ allspace }) => ({ allspace, })) class RefreshTable extends PureComponent { static defaultProps = { search: true, searchPlaceHolder: '按名稱(chēng)模糊搜索', save: true, scrollFlag: false, scrollY: 0, scroll: false, }; constructor(props) { super(props); this.state = { datecolumns: [], width: 0, columnVisible: false, }; } componentDidMount() { this.initData(); } componentWillReceiveProps(nextProps) { this.initData(); // todo 關(guān)于這兒是否有bug測(cè)試 // clean state const { datecolumns } = this.state; if (nextProps.columns.length > 0 && datecolumns.length > 0) { const datecolumnsRefresh = nextProps.columns.map((i, idx) => { let nowData = ''; datecolumns.forEach(item => { if (item.dataIndex === i.dataIndex) { nowData = item; } }); const { show } = nowData; const obj = { ...nowData, ...i, show, }; return obj; }); this.setState({ datecolumns: datecolumnsRefresh, }); } } initData = () => { const { scrollFlag, columns, save, pathName } = this.props; let { width } = this.state; const initData = initColumns(columns); let datecolumns = null; if (save) { datecolumns = saveColumns(initData, pathName); } else { datecolumns = initData; } if (scrollFlag) { datecolumns.forEach(item => { if (item.show) { width += item.width; } }); this.setState({ width, datecolumns, }); } else { this.setState({ datecolumns, }); } }; defaultList = () => { const { datecolumns = [] } = this.state; const defaultCheckedList = []; datecolumns.forEach(item => { if (item.show) { defaultCheckedList.push(item.dataIndex); } }); return defaultCheckedList; }; handleTableChange = (pagination, filters, sorter) => { const { onChange } = this.props; const { datecolumns } = this.state; if (onChange) { onChange(pagination, filters, sorter); } if (sorter.field) { datecolumns.forEach(item => { item.sortOrder = false; item.dataIndex === sorter.field && (item.sortOrder = sorter.order); }); this.setState({ datecolumns, }); } else { datecolumns.forEach(item => { item.sortOrder = false; }); this.setState({ datecolumns, }); } }; handleColumnVisible = () => {}; showTableColumn = visible => { this.setState({ columnVisible: visible, }); }; changeColumn = value => { const { scrollFlg, pathName } = this.props; const { datecolumns } = this.state; let width = 0; const arr = []; datecolumns.forEach(item => { const obj = { ...item, }; if (value.indexOf(item.dataIndex) !== -1) { obj.show = true; if (scrollFlg) { width += obj.width; } } else { obj.show = false; } arr.push(obj); }); this.setState({ datecolumns: arr, width, }); const storage = arr.map(i => { return { dataIndex: i.dataIndex, show: i.show, }; }); localStorage.setItem(pathName, JSON.stringify(storage)); }; handleCancel = () => { this.setState({ columnVisible: false, }); }; handleRefresh = () => { const { handleRefresh } = this.props; const { datecolumns } = this.state; if (handleRefresh) { datecolumns.forEach(item => { item.sortOrder = false; }); this.setState({ datecolumns, }); handleRefresh(); } }; render() { const { scroll, scrollY, data, children, rowKey, searchPlaceHolder, tableParam, handleRefresh, handleSearch, changeSearch, pageSizeArr, searchWidth, ...rest } = this.props; const { resultList = [], totalsize = 0 } = data; const { columnVisible, datecolumns, width } = this.state; const defaultScroll = {}; if (scroll) { defaultScroll.x = width; } if (scrollY) { defaultScroll.y = scrollY; } const paginationProps = { showSizeChanger: true, showQuickJumper: true, showTotal: () => `共${totalsize}條記錄 第${tableParam.pageNo}/${Math.ceil( totalsize / tableParam.pageSize )}頁(yè)`, current: tableParam.pageNo, pageSize: tableParam.pageSize, total: totalsize, pageSizeOptions: pageSizeArr ? pageSizeArr : ['10', '20', '30', '40'], }; const checkValue = this.defaultList(); return ( <div className={styles.RefreshTable}> <div className={styles.tableListOperator}> {handleRefresh && ( <Button icon="reload" type="primary" onClick={this.handleRefresh} className={styles.tableRefresh} /> )} <Popover onVisibleChange={this.showTableColumn} placement="bottomLeft" visible={columnVisible} trigger="click" className={styles.dropdown} content={ <Checkbox.Group className={styles.selsectMenu} defaultValue={checkValue} onChange={this.changeColumn} > {datecolumns.map(item => ( <Col key={`item_${item.dataIndex}`} style={{ marginBottom: '8px' }}> <Checkbox value={item.dataIndex} key={item.dataIndex} disabled={item.disabled} className={styles.checkboxStyle} > {item.title} </Checkbox> </Col> ))} </Checkbox.Group> } > <Button className={styles.refreshButton}> <Icon type="appstore" theme="filled" style={{ fontSize: '14px' }} /> </Button> </Popover> {children ? <Fragment>{children}</Fragment> : null} {handleSearch && ( <Search placeholder={searchPlaceHolder} style={{ width: searchWidth ? searchWidth : '200px', marginRight: '10px' }} value={tableParam.filterParam} onChange={changeSearch} onSearch={value => handleSearch(value)} /> )} </div> <Table {...rest} rowKey={ rowKey || (record => record.id || (record.namespace ? record.name + '/' + record.namespace : record.name)) } size="middle" loading={tableParam.loading} dataSource={resultList} pagination={paginationProps} scroll={defaultScroll} columns={datecolumns.filter(item => item.show === true)} onChange={this.handleTableChange} /> </div> ); } } export default RefreshTable;
調(diào)用組件頁(yè)面
import React, { PureComponent, Fragment } from 'react'; import { connect } from 'dva'; import { formatMessage } from 'umi-plugin-react/locale'; import { Card, Form, Icon, Tooltip } from 'antd'; import RefreshTable from '@/components/RefreshTable'; import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import SearchSelect from '@/components/SearchSelect'; import { getAuthority } from '@/utils/authority'; import moment from 'moment'; @connect(({ stateless, allspace, loading }) => ({ stateless, allspace, loading: loading.models.stateless, stretchLoading: loading.effects['stateless/stretch'], })) @Form.create() class Stateless extends PureComponent { state = { pageSize: 10, pageNo: 1, filterParam: '', sortBy: '', sortFlag: 'desc', namespace: '', }; columns = [ { title: '名稱(chēng)', dataIndex: 'name', disabled: true, sorter: true, }, { title: '命名空間', dataIndex: 'namespace', width: 105, textWrap: 'ellipsis', }, { title: '更新次數(shù)', dataIndex: 'observedGeneration', sorter: true, width: 100, }, { title: '副本數(shù)', dataIndex: 'replicas', sorter: true, width: 90, }, { title: '更新副本數(shù)', dataIndex: 'updatedReplicas', sorter: true, width: 115, render: text => <span>{text ? text : 0}</span>, }, { title: '就緒副本', dataIndex: 'readyReplicas', sorter: true, width: 100, render: text => <span>{text ? text : 0}</span>, }, { title: '可用副本', dataIndex: 'availableReplicas', sorter: true, width: 100, render: text => <span>{text ? text : 0}</span>, }, { title: '創(chuàng)建時(shí)間', dataIndex: 'createTime', sorter: true, width: window.screen.width <= 1366 ? 95 : 155, render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>, }, { title: '操作', dataIndex: 'operate', disabled: true, width: 150, }, ]; componentDidMount() { this.getStatelessList(); } getStatelessList = value => { const { dispatch } = this.props; let params = {}; if (!value) { const { pageSize, pageNo, filterParam, sortBy, sortFlag, namespace } = this.state; params = { pageSize, pageNo, keyword: filterParam.trim(), sortBy, sortFlag, namespace, }; } else { params = value; } dispatch({ type: 'stateless/fetch', payload: params, }); }; handleStandardTableChange = (pagination, filtersArg, sorter) => { const { filterParam, namespace } = this.state; const params = { pageNo: pagination.current, pageSize: pagination.pageSize, keyword: filterParam.trim(), namespace, }; this.setState({ pageNo: pagination.current, pageSize: pagination.pageSize, }); if (sorter.field) { params.sortBy = sorter.field; params.sortFlag = sorter.order.slice(0, -3); this.setState({ sortBy: sorter.field, sortFlag: sorter.order.slice(0, -3), }); } else { this.setState({ sortBy: '', sortFlag: '', }); } this.getStatelessList(params); }; handleRefresh = () => { const params = { keyword: '', pageSize: 10, pageNo: 1, namespace: '', }; this.setState({ filterParam: '', pageNo: 1, pageSize: 10, namespace: '', sortBy: '', sortFlag: '', }); this.getStatelessList(params); }; handleSearch = value => { const { pageSize, sortBy, sortFlag, namespace } = this.state; const params = { keyword: value.trim(), pageSize, pageNo: 1, sortBy, sortFlag, namespace, }; this.setState({ filterParam: value, pageNo: 1, }); this.getStatelessList(params); }; changeSearch = e => { this.setState({ filterParam: e.target.value, }); }; handleSpaceChange = value => { const { filterParam, sortBy, sortFlag, pageSize } = this.state; const params = { keyword: filterParam.trim(), pageSize, pageNo: 1, namespace: value === '' ? '' : value, sortBy, sortFlag, }; this.setState({ pageNo: 1, namespace: value === '' ? '' : value, }); this.getStatelessList(params); }; render() { const { stateless: { data }, loading, route, allspace, stretchLoading, } = this.props; const { filterParam, pageSize, pageNo, namespace, current = {} } = this.state; const tableParam = { pageNo, pageSize, filterParam, loading, }; const keyArr = []; if (data && data.data && data.data.resultList) { data.data.resultList .filter(item => item.message) .forEach(item => { keyArr.push(`${item.name}/${item.namespace}`); }); } return ( <PageHeaderWrapper content={`${formatMessage({ id: `statelessCaption` })}`}> <Card bordered={false}> <RefreshTable tableParam={tableParam} data={data && data.data ? data.data : {}} rowKey={record => `${record.name}/${record.namespace}`} pathName={route.name} columns={this.columns} changeSearch={this.changeSearch} onChange={this.handleStandardTableChange} handleSearch={this.handleSearch} handleRefresh={this.handleRefresh} expandIcon={record => CustomExpandIcon(record)} expandedRowKeys={keyArr} expandedRowRender={record => ( <Fragment> {record.message ? <span style={{ color: 'red' }}>{record.message}</span> : null} </Fragment> )} > <SearchSelect handleSpaceChange={ 'admin'.indexOf(getAuthority()) !== -1 ? this.handleSpaceChange : false } namespace={namespace} spaceData={allspace.namespace ? allspace.namespace.data.resultList : []} /> </RefreshTable> </Card> </PageHeaderWrapper> ); } } export default Stateless;
以上這篇ant design的table組件實(shí)現(xiàn)全選功能以及自定義分頁(yè)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
基于Vue 擼一個(gè)指令實(shí)現(xiàn)拖拽功能
這篇文章主要介紹了Vue 指令實(shí)現(xiàn)拖拽功能,實(shí)現(xiàn)原理很簡(jiǎn)單,文中通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10關(guān)于vue.js中實(shí)現(xiàn)方法內(nèi)某些代碼延時(shí)執(zhí)行
今天小編就為大家分享一篇關(guān)于vue.js中實(shí)現(xiàn)方法內(nèi)某些代碼延時(shí)執(zhí)行,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11Vue3?接入?i18n?實(shí)現(xiàn)國(guó)際化多語(yǔ)言案例分析
在?Vue.js?3?中實(shí)現(xiàn)網(wǎng)頁(yè)的國(guó)際化多語(yǔ)言,最常用的包是?vue-i18n,通常我們會(huì)與?vue-i18n-routing?一起使用,這篇文章主要介紹了Vue3?如何接入?i18n?實(shí)現(xiàn)國(guó)際化多語(yǔ)言,需要的朋友可以參考下2024-07-07vuejs前后端數(shù)據(jù)交互之從后端請(qǐng)求數(shù)據(jù)的實(shí)例
今天小編就為大家分享一篇vuejs前后端數(shù)據(jù)交互之從后端請(qǐng)求數(shù)據(jù)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08Vue實(shí)現(xiàn)記住賬號(hào)密碼功能的操作過(guò)程
這篇文章主要介紹了Vue實(shí)現(xiàn)記住賬號(hào)密碼功能,用戶(hù)登錄時(shí)若勾選“記住我”功能選項(xiàng),則將登錄名和密碼(加密后)存入本地緩存,下次登錄頁(yè)面加載時(shí)自動(dòng)獲取保存好的賬號(hào)和密碼(需解密),回顯到登錄輸入框中,下面分享我實(shí)現(xiàn)的具體步驟,需要的朋友可以參考下2022-07-07element-ui中樣式覆蓋問(wèn)題的方法總結(jié)
我們?cè)谑褂胑lement-ui的時(shí)候經(jīng)常會(huì)遇到需要修改組件默認(rèn)樣式,下面這篇文章主要給大家介紹了關(guān)于element-ui中樣式覆蓋問(wèn)題的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03Vue.js組件tree實(shí)現(xiàn)無(wú)限級(jí)樹(shù)形菜單
這篇文章主要為大家詳細(xì)介紹了Vue.js組件tree實(shí)現(xiàn)無(wú)限級(jí)樹(shù)形菜單代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12