You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在shadcn数据表格中向react-table ColumnDef传递Props

解决Shadcn Data Table传递URL查询参数到ColumnDef的问题

核心思路

把列定义改成接收参数的函数,在页面组件里拿到URL查询参数后,调用这个函数生成带参数的列配置,就能在cell组件里直接用传递的参数拼接链接了。

具体修改步骤

1. 修改columns.tsx,将列定义改为带参数的函数

// columns.tsx
import { ColumnDef } from "@tanstack/react-table";
import { Button } from "@/components/ui/button";

// 定义你的数据类型
export interface Repo {
  id: string;
  name: string;
  // 其他业务字段...
}

// 改成接收外部参数的函数,返回ColumnDef数组
export const getColumns = (owner: string): ColumnDef<Repo>[] => [
  {
    accessorKey: "name",
    header: "仓库名称",
    cell: ({ row }) => {
      // 直接使用传递进来的owner拼接目标链接
      const repoUrl = `https://github.com/${owner}/${row.getValue("name")}`;
      return (
        <Button variant="link" onClick={() => window.open(repoUrl, "_blank")}>
          {row.getValue("name")}
        </Button>
      );
    },
  },
  // 其他列定义...
];

2. 在page.tsx中获取URL参数并生成列配置

// page.tsx
import { useSearchParams } from "react-router-dom";
import { DataTable } from "@/components/data-table";
import { getColumns, Repo } from "./columns";

export default function ReposPage() {
  // 从URL查询参数中取出owner值
  const [searchParams] = useSearchParams();
  const owner = searchParams.get("owner") || "default-owner";

  // 调用函数生成带参数的列配置
  const columns = getColumns(owner);

  // 示例业务数据
  const data: Repo[] = [
    { id: "1", name: "repo-1" },
    { id: "2", name: "repo-2" },
  ];

  return <DataTable columns={columns} data={data} />;
}

常见失败原因排查

之前用函数方式失败,大概率是以下两种情况:

  • 没有正确传递参数:比如调用函数时没拿到有效的searchParam值,或者参数传递路径出错
  • 类型定义不匹配:没有给函数指定参数类型,或者ColumnDef的泛型和数据接口不对应,导致TS报错

内容的提问来源于stack exchange,提问作者Kalaschnik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 18:44:57