当前位置: 首页 > news >正文

react实现table可拖拽表头(给react-jss样式传递参数、滚动条样式)

目录

  • react实现table可拖拽表头
    • 安装依赖
    • resizableTitle / index.tsx
    • drapTable.tsx
    • 使用DragTable 组件
    • 滚动条样式
    • 效果

react实现table可拖拽表头

安装依赖

yarn add react-resizable 
yarn add react-jss

resizableTitle / index.tsx


import { createUseStyles } from 'react-jss';
import { Resizable } from 'react-resizable';const useResizableTitleStyles = createUseStyles({resizableHandle : {position: 'absolute',right: '-5px',bottom: 0,zIndex: 1,width: '10px',height: '100%',cursor: 'col-resize'}
});
// 表头拖拽组件
export const ResizableTitle = ({ onResize, width, isNotResizable, ...restProps }) => {const classes = useResizableTitleStyles();// 新增处理函数,用于阻止事件冒泡const stopPropagation = (event) => event.stopPropagation();// isNotResizable 或者 没有宽度 不可拖拽console.log('isNotResizable',isNotResizable, width, 'restProps', restProps);if (!width || isNotResizable) { return (<th {...restProps} />) };return (<Resizablewidth={width}height={0}handle={<span className={classes.resizableHandle} onClick={stopPropagation} />}onResize={onResize}draggableOpts={{ enableUserSelectHack: false }}><th {...restProps} style={{ ...restProps?.style, userSelect: 'none' }} /></Resizable>);
};

drapTable.tsx

import type { TableProps } from 'antd';
import { Table } from 'antd';
import { useState, useMemo, useEffect, useCallback } from 'react';
import type { ColumnType } from 'antd/lib/table';
import { ResizableTitle } from './resizableTitle/index';
import { createUseStyles } from 'react-jss';interface TableStylesProps {paddingVertical?: number;paddingHorizontal?: number;
}
// 设置table的 cell里面的 padding
const useTableStyles = createUseStyles({base_table_com: {'& .ant-table-thead > tr > th, & .ant-table-tbody > tr > td, & .ant-table tfoot > tr > th, & .ant-table tfoot > tr > td':{padding: (cProps: TableStylesProps) =>`${cProps.paddingVertical ?? 10}px ${cProps.paddingHorizontal ?? 12}px`,},},
});export const DragTable = <RecordType extends Record<string, any> = any>(props: ICommonTableProps<RecordType>,
) => {const {showTotalNum = true,pagination,hidePagination,paddingVertical,paddingHorizontal,} = props;const [tablePagination, setTablePagination] = useState<any>(pagination);const classes = useTableStyles({ paddingVertical, paddingHorizontal });const { columns } = props;// 设置可拖拽的表头const [rescolumns, setResColumns] = useState<ColumnType<any>[]>(columns.filter((column) => !column.hide) || [],);// 拖拽后 重新设置列表宽度const handleResize = useCallback((index) => {return (txt: any, Resize: any) => {const temp = [...rescolumns];temp[index] = { ...temp[index], width: Resize.size.width };setResColumns(temp);};},[rescolumns],);// 把 columns 设置可拖拽的cellconst columnsMap: any[] = useMemo(() => {return (rescolumns?.map((column: any, index) => {return {...column,onHeaderCell: (col: any) => ({width: col.width,onResize: handleResize(index),isNotResizable: col.isNotResizable}),};}) || []);}, [rescolumns, handleResize]);useEffect(() => {const showTotal = {showTotal: (total: number, range: number[]) => {if (showTotalNum) {return `共{${props.pagination ? props.pagination?.total : 0}}条结果`;} else {return '';}},};if (!hidePagination) {setTablePagination(Object.assign({}, pagination ?? {}, showTotal));} else {setTablePagination(false);}}, [hidePagination, pagination, props.pagination, showTotalNum]);return (<Table{...props}columns={columnsMap}pagination={tablePagination}components={{ header: { cell: ResizableTitle } }}className={classes.base_table_com}/>);
};interface CommonColumn<T> extends ColumnType<T> {hide?: boolean;
}export interface ICommonTableProps<RecordType> extends TableProps<RecordType> {showTotalNum?: boolean;hidePagination?: boolean;columns: CommonColumn<RecordType>[]; // 重写 columns 类型paddingVertical?: number; // 上下paddingpaddingHorizontal?: number;// 左右padding
}

使用DragTable 组件

import { createUseStyles } from 'react-jss';
import { useEffect, useMemo, useState, useRef } from 'react';
import { DragTable } from './drapTable';
import { Space } from "antd"const TablePage = () => {const columns = [{title: '操作',width: 60,isNotResizable: true, // 设置操作栏固定不可拖拽render: (_, record) => (<Space size="middle"><a>删除</a></Space>),},{title: '编码',dataIndex: 'code',width: 100,},{title: '名称',width: 100,dataIndex: 'name',},{title: '测试',dataIndex: 'test',width: 400,},{title: '描述',dataIndex: 'des',width: 400,},];const dataSource = [{ id: 1, code: '001', name: '我是name1', test: '测试一下1', des: '描述一下' },{ id: 2, code: '002', name: '我是name2', test: '测试一下2', des: '描述一下2' },{ id: 3, code: '003', name: '我是name3', test: '测试一下3', des: '描述一下3' },{ id: 4, code: '004', name: '我是name4', test: '测试一下4', des: '描述一下4' },{ id: 5, code: '005', name: '我是name5', test: '测试一下5', des: '描述一下5' },{ id: 6, code: '006', name: '我是name6', test: '测试一下6', des: '描述一下6' },{ id: 7, code: '007', name: '我是name7', test: '测试一下7', des: '描述一下7' },{ id: 8, code: '008', name: '我是name8', test: '测试一下8', des: '描述一下8' },{ id: 9, code: '009', name: '我是name9', test: '测试一下9', des: '描述一下9' },];return (<><DragTablerowKey="id"paddingVertical={8}paddingHorizontal={10}columns={columns}dataSource={dataSource}scroll={{ x: 'max-content', y : 250 }}/></>);
};
export default TablePage;

滚动条样式


/* 设置滚动条的宽度和背景色 */
::-webkit-scrollbar {width: 6px; /* 垂直滚动条的宽度 */height: 6px; /* 水平滚动条的宽度 */background-color: #f5f5f5; /* 滚动条的背景色 */
}/* 设置滚动条的滑块 */
::-webkit-scrollbar-thumb {background-color: #999; /* 滑块的背景色 */border-radius: 4px; /* 滑块的圆角 */cursor: pointer;
}/* 设置滚动条的轨道 */
::-webkit-scrollbar-track {background-color: #f5f5f5; /* 轨道的背景色 */
}

效果

在这里插入图片描述

http://www.lryc.cn/news/352859.html

相关文章:

  • 如何跨过robots协议的限制爬取内容?
  • Parasoft C++Test软件静态分析操作指南_编码规范/标准检查
  • [AIGC] CompletableFuture如何实现任务链式调用?
  • 神奇动物在哪里?斯洛文尼亚旅游之野生动物寻踪
  • 电商项目之有趣的支付签名算法
  • Web开发核心
  • 【Python】【Scrapy 爬虫】理解HTML和XPath
  • 【CTF Web】CTFShow web5 Writeup(SQL注入+PHP+位运算)
  • LeetCode 968.监控二叉树 (hard)
  • 数理逻辑:1、预备知识
  • 14-云原生监控体系-Redis_exporter 监控 MySQL[部署Dashborad告警规则实战]
  • DOS学习-目录与文件应用操作经典案例-xcopy
  • Midjourney是一个基于GPT-3.5系列接口开发的免费AI机器人
  • v-model详解
  • ArcGIS中分割与按属性分割的区别
  • 就业班 第三阶段(ELK) 2401--5.20 day1 ELK 企业实战 ES+head+kibana+logstash部署(最大集群)
  • PCM和QAM
  • Mongodb分布式id
  • AI模型抉择:开源VS闭源,谁主沉浮?
  • 佩戴安全头盔监测识别摄像机
  • 5.24学习记录
  • 创建FreeRTOS工程
  • HTML中 video标签样式铺满全屏
  • vue项目移动端商场
  • Golang | Leetcode Golang题解之第97题交错字符串
  • 2024电工杯B题:大学生平衡膳食食谱的优化设计及评价
  • 齐护K210系列教程(三十二)_在线模型训练
  • 碌时刻必备!微信自动回复让你告别消息堆积
  • 【ARM 裸机】按键输入
  • 站在ESG“20+”新起点上,看中国ESG先锋探索力量