用react-custom-scrollbars插件美化 Ant Design Table 滚动条

mac2024-03-27  29

Ant Design Table 自带的滚动条不太美观,我们来用react-custom-scrollbars插件给它美化一下。

先看一下最终的效果,增加一下信心:

安装 react-custom-scrollbars

不多说了,直接安装插件

npm install react-custom-scrollbars --save

引入滚动条插件和表格组件,写个DataTable组件

注意:

当表格重新渲染的时候,滚动条会重新滚动到顶部,之前滚动的位置会消失。所以我们需要在滚动条停止的时候记下它的位置,当下次更新时,重新定位滚动条的位置。

import React from 'react'; import { Table } from 'antd'; import { Scrollbars } from 'react-custom-scrollbars'; // 数据表头 const columns = [ { title: '姓名', dataIndex: 'name', key: 'name', }, { title: '年龄', dataIndex: 'age', key: 'age', }, { title: '住址', dataIndex: 'address', key: 'address', }, // 增加空白列 {} ]; // 滚动条参数 const scroll = { // 如果最终结果表格内容与表格头部无法对齐。 // 表格头需要增加空白列,弹性布局 width: '100%', // 最大高度,内容超出该高度会出现滚动条 height: 100, } class DataTable extends React.Component{ // 滚动结束,记下滚动位置 handleScrollStop = () => { if (this.scrollbarsRef.current){ this.scrollTop = this.scrollbarsRef.current.getScrollTop(); } }; componentDidMount() { // 覆盖ant design 自带滚动条样式 document.querySelector('.ant-table-scroll > .ant-table-body').style.overflow='hidden'; // 滚动条组件ref,重新设置滚动位置 this.scrollbarsRef = React.createRef(); } // 组件重新渲染,重新设置滚动条的位置 componentDidUpdate(prevProps, prevState, snapshot) { if (this.scrollbarsRef.current){ this.scrollbarsRef.current.scrollTop(this.scrollTop); } } render() { const dataSource = [ { key: '1', name: '胡彦斌', age: 32, address: '西湖区湖底公园1号', }, { key: '2', name: '胡彦祖', age: 42, address: '西湖区湖底公园1号', }, ]; // 词法作用域 const self = this; // 用react-custom-scrollbars包裹住表格内容 const components = { table (props) { const { className } = props; return ( <Scrollbars style={scroll} onScrollStop={self.handleScrollStop} ref={ self.scrollbarsRef } > <table className={className}> { props.children } </table> </Scrollbars> ) } }; return ( <Table dataSource={dataSource} columns={columns} // 此scroll选项必须开启,宽高与react-custom-scrollbars插件一致 scroll={{y: scroll.height, x: scroll.width}} // 将react-custom-scrollbars组件插入到表格中 components={components} /> ) } } export default DataTable;
最新回复(0)