表格组件添加固定到边缘功能

This commit is contained in:
2026-03-27 18:02:38 +08:00
parent 523d46874b
commit 1e6b307586
2 changed files with 48 additions and 2 deletions

View File

@@ -90,6 +90,8 @@ export default function UserPage() {
format(new Date(row.original.created_at), "yyyy-MM-dd HH:mm"),
},
{
id: "action",
meta: { pin: "right" },
header: "操作",
cell: ctx => (
<Button

View File

@@ -1,10 +1,12 @@
import {
type Column,
type ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table"
import { Loader } from "lucide-react"
import { type CSSProperties, useCallback, useMemo } from "react"
import { Pagination, type PaginationProps } from "@/components/ui/pagination"
import {
TableBody,
@@ -44,8 +46,46 @@ export function DataTable<T extends Record<string, unknown>>(
},
columnFilters: [],
},
initialState: {
columnPinning: {
left: props.columns
.map(column =>
column.meta?.pin === "left"
? column.id || column.accessorKey
: undefined,
)
.filter(Boolean),
right: props.columns
.map(column =>
column.meta?.pin === "right"
? column.id || column.accessorKey
: undefined,
)
.filter(Boolean),
},
},
})
const pinStyle = (column: Column<T>) => {
const pinned = column.getIsPinned()
if (!pinned) return {}
return {
position: pinned ? ("sticky" as const) : undefined,
backgroundColor: "white",
zIndex: 1,
...{
left: {
left: column.getStart(pinned),
boxShadow: "inset 1px 0 var(--border)",
},
right: {
right: column.getAfter(pinned),
boxShadow: "inset 1px 0 var(--border)",
},
}[pinned],
} as CSSProperties
}
return (
<div className={cn("flex flex-col gap-3", props.classNames?.root)}>
{/* 数据表 */}
@@ -55,7 +95,11 @@ export function DataTable<T extends Record<string, unknown>>(
{table.getHeaderGroups().map(group => (
<TableRow key={group.id}>
{group.headers.map(header => (
<TableHead key={header.id} colSpan={header.colSpan}>
<TableHead
key={header.id}
colSpan={header.colSpan}
style={pinStyle(header.column)}
>
{header.isPlaceholder
? null
: flexRender(
@@ -94,7 +138,7 @@ export function DataTable<T extends Record<string, unknown>>(
className={cn("h-14", props.classNames?.dataRow)}
>
{row.getVisibleCells().map(cell => (
<TableCell key={cell.id}>
<TableCell key={cell.id} style={pinStyle(cell.column)}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),