有了这个反应组件:
import rawd from '../../data.json';
import { flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table"
import { useState } from "react";
const columns = [
{
accessorKey: 'id',
id: 'id',
header: 'Id',
cell: props => <p>{props.getValue()}</p>
},
{
accessorKey: 'mail',
id: 'email',
header: 'Email',
cell: props => <p>{props.getValue()}</p>
},
{
accessorKey: 'name.first_name',
id: 'first_name',
header: 'First Name',
cell: props => <p>{props.getValue()}</p>
},
{
accessorKey: 'name.last_name',
id: 'last_name',
header: 'Last Name',
cell: props => <p>{props.getValue()}</p>
},
{
accessorKey: 'date_of_birth',
id: 'date_of_birth',
header: 'Date of birth',
cell: props => <p>{props.getValue()}</p>
},
];
function NikitaDev() {
const [data] = useState(rawd);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
columnResizeMode: 'onChange'
});
console.log(table.getHeaderGroups());
return (
<div className="overflow-x-auto flex flex-col m-[1rem]">
<table className='w-full text-left text-sm text-gray-500'>
<thead className='text-xs text-gray-700 uppercase bg-gray-50'>
{table.getHeaderGroups().map(hg => (
<tr key={hg.id}>
{hg.headers.map(h => (
<th key={h.id} className='relative border px-6 py-3'>
{h.column.columnDef.header}
<div
onMouseDown={h.getResizeHandler()}
onTouchStart={h.getResizeHandler()}
className="absolute top-0 right-0 h-full w-[5px] hover:bg-gray-300 cursor-col-resize"
>
</div>
</th>
))}
</tr>
))}
</thead>
<tbody>
{table.getRowModel().rows.map(row => (
<tr id={row.id} className='odd:bg-white even:bg-gray-50'>
{row.getVisibleCells().map(c => (
<td key={c.id} className='border p-[0.25rem]'>
{flexRender(
c.column.columnDef.cell,
c.getContext()
)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)
}
export default NikitaDev
我希望通过拖动边缘的表格标题 - 这个div:
<div
onMouseDown={h.getResizeHandler()}
onTouchStart={h.getResizeHandler()}
className="absolute top-0 right-0 h-full w-[5px] hover:bg-gray-300 cursor-col-resize"
>
</div>
应该调整列的大小。但事实并非如此。为什么?
您似乎尚未将列大小定义传递到表中。根据文档:
这些事件处理程序只是调用其他内部 API 来更新列大小调整状态并重新呈现表的便捷函数。
如果我们早一点阅读文档:
列大小 API
要将列的大小应用于列头单元格、数据单元格或页脚单元格,您可以使用以下 API:
header.getSize() column.getSize() cell.column.getSize()
如何将这些尺寸样式应用到标记中取决于您,但使用 CSS 变量或内联样式来应用列尺寸是很常见的。
<th key={header.id} colSpan={header.colSpan} style={{ width: `${header.getSize()}px` }}
因此,我们可以将
header.getSize()
调用添加到表头,以便列大小调整状态反映在界面中:
{hg.headers.map(h => (
<th
key={h.id}
className='relative border px-6 py-3'>
style={{ width: `${header.getSize()}px` }}
>
{h.column.columnDef.header}
请参阅此工作示例 在此 StackBlitz 项目中。