所有分类
  • 所有分类
  • Html5资源
  • React资源
  • Vue资源
  • Php资源
  • ‌小程序资源
  • Python资源

Table-Render:基于 JSON Schema 的高性能 React 动态表格渲染器

简介

Table-Render 是一个基于 JSON Schema 的动态表格渲染器,支持通过配置化的方式快速生成复杂的表格界面。它提供了丰富的表格功能、灵活的列配置系统和强大的数据处理能力。

核心特性

  • JSON Schema 驱动:基于标准的 JSON Schema 规范
  • 虚拟滚动支持:内置虚拟滚动技术,轻松处理大数据量
  • 丰富的列类型:内置多种列类型,支持自定义列渲染器
  • 灵活的布局:支持固定列、表头固定、响应式设计
  • 强大的数据处理:内置排序、筛选、分页等功能
  • TypeScript 支持:完整的类型定义

安装

npm install table-render

基本用法

简单示例

import TableRender from "table-render";

const BasicExample = () => {
  // Define search schema for the search form
  const searchSchema = {
    type: "object",
    properties: {
      name: {
        title: "姓名",
        type: "string",
      },
      status: {
        title: "状态",
        type: "string",
        enum: ["active", "disabled"],
        enumNames: ["活跃", "禁用"],
      },
    },
  };

  // Define table columns
  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "年龄",
      dataIndex: "age",
      key: "age",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => (
        <span
          style={{
            color: status === "active" ? "green" : "red",
            padding: "2px 8px",
            borderRadius: "4px",
            backgroundColor: status === "active" ? "#f6ffed" : "#fff2f0",
            border: `1px solid ${status === "active" ? "#b7eb8f" : "#ffccc7"}`,
          }}
        >
          {status === "active" ? "活跃" : "禁用"}
        </span>
      ),
    },
    {
      title: "操作",
      key: "actions",
      render: (_, record) => (
        <div>
          <button
            onClick={() => handleAction("edit", record)}
            style={{
              marginRight: 8,
              color: "#1890ff",
              border: "none",
              background: "none",
              cursor: "pointer",
            }}
          >
            编辑
          </button>
          <button
            onClick={() => handleAction("delete", record)}
            style={{
              color: "#ff4d4f",
              border: "none",
              background: "none",
              cursor: "pointer",
            }}
          >
            删除
          </button>
        </div>
      ),
    },
  ];

  // Mock API function with search functionality
  const api = (params) => {
    console.log("API called with params:", params);

    // 完整的数据源
    const allData = [
      {
        id: "1",
        name: "张三",
        age: 28,
        email: "zhangsan@example.com",
        status: "active",
      },
      {
        id: "2",
        name: "李四",
        age: 32,
        email: "lisi@example.com",
        status: "disabled",
      },
    ];

    // 根据查询参数过滤数据
    let filteredData = allData;

    if (params && Object.keys(params).length > 0) {
      filteredData = allData.filter((item) => {
        let match = true;

        // 按姓名过滤
        if (params.name && params.name.trim()) {
          match = match && item.name.includes(params.name.trim());
        }

        // 按状态过滤
        if (params.status) {
          match = match && item.status === params.status;
        }

        return match;
      });
    }

    return Promise.resolve({
      data: filteredData,
      total: filteredData.length,
    });
  };

  const handleAction = (action, record) => {
    console.log("Action:", action, "Record:", record);
  };

  return (
    <TableRender
      search={{ schema: searchSchema }}
      request={api}
      columns={columns}
      title="用户列表"
      pagination={{ pageSize: 10 }}
    />
  );
};

export default BasicExample;

API 参考

TableRender Props

属性名类型默认值描述
tableobject表格实例,通过 useTable() 创建
schemaobjectJSON Schema 配置对象
dataSourcearray[]表格数据源
onActionfunction操作按钮点击回调函数
paginationobjectfalse分页配置
virtualobjectfalse虚拟滚动配置
scrollobject滚动配置
loadingbooleanfalse加载状态
rowSelectionobject行选择配置
expandableobject展开行配置

useTable Hook

useTable Hook 提供了表格状态管理的方法:

方法名参数返回值描述
getSelectedRows()array获取选中的行
setSelectedRows(rows: array)void设置选中的行
clearSelection()void清空选中状态
getTableData()array获取表格数据
setTableData(data: array)void设置表格数据
refresh()void刷新表格
exportData(format: string)void导出数据

使用示例

const table = useTable();

// 获取选中的行
const selectedRows = table.getSelectedRows();

// 设置表格数据
table.setTableData(newData);

// 清空选中状态
table.clearSelection();

列类型配置

基础列类型

// 文本列
{
  title: "姓名",
  dataIndex: "name",
  type: "text",
  width: 120,
  ellipsis: true
}

// 数字列
{
  title: "价格",
  dataIndex: "price",
  type: "number",
  width: 100,
  precision: 2,
  prefix: "¥"
}

// 日期时间列
{
  title: "创建时间",
  dataIndex: "createTime",
  type: "datetime",
  width: 180,
  format: "YYYY-MM-DD HH:mm:ss"
}

// 标签列
{
  title: "状态",
  dataIndex: "status",
  type: "tag",
  width: 100,
  options: [
    { label: "进行中", value: "progress", color: "blue" },
    { label: "已完成", value: "completed", color: "green" }
  ]
}

// 操作列
{
  title: "操作",
  key: "actions",
  type: "actions",
  width: 150,
  actions: [
    { label: "编辑", type: "primary", action: "edit" },
    { label: "删除", type: "danger", action: "delete" }
  ]
}

高级功能

表头固定和列固定

<TableRender
  schema={schema}
  dataSource={dataSource}
  scroll={{ y: 400 }}
  sticky={{ offsetHeader: 64 }}
/>

// 列固定
{
  title: "姓名",
  dataIndex: "name",
  fixed: "left"  // 左侧固定
}
{
  title: "操作",
  key: "actions",
  fixed: "right"  // 右侧固定
}

行选择

<TableRender
  schema={schema}
  dataSource={dataSource}
  rowSelection={{
    type: "checkbox",
    selectedRowKeys: selectedKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedKeys(selectedRowKeys);
    },
  }}
/>

排序和筛选

// 排序
{
  title: "年龄",
  dataIndex: "age",
  sorter: true,
  defaultSortOrder: "ascend"
}

// 筛选
{
  title: "状态",
  dataIndex: "status",
  filters: [
    { text: "活跃", value: "active" },
    { text: "禁用", value: "disabled" }
  ],
  onFilter: (value, record) => record.status === value
}

数据导出

const handleExport = (format) => {
  const selectedRows = table.getSelectedRows();
  const exportData = selectedRows.length > 0 ? selectedRows : dataSource;

  switch (format) {
    case "excel":
      table.exportToExcel(exportData, "用户数据.xlsx");
      break;
    case "csv":
      table.exportToCSV(exportData, "用户数据.csv");
      break;
  }
};

性能优化

虚拟滚动

<TableRender
  schema={schema}
  dataSource={largeDataSource}
  virtual={{
    enabled: true,
    height: 600,
    itemHeight: 54,
    buffer: 10,
  }}
  rowKey="id"
/>

常见问题

Q: 如何处理大数据量渲染?

A: 使用虚拟滚动功能:

<TableRender
  virtual={{
    enabled: true,
    height: 600,
    itemHeight: 54,
  }}
  dataSource={largeDataSource}
/>

Q: 如何自定义列渲染?

A: 使用 render 函数:

{
  title: "自定义列",
  dataIndex: "custom",
  render: (value, record, index) => {
    return <CustomComponent value={value} record={record} />;
  }
}

Q: 表格性能优化方法?

A:

  1. 使用虚拟滚动处理大数据
  2. 合理使用 React.memo 优化组件渲染
  3. 使用 rowKey 提供稳定的 key
  4. 分页加载数据,避免一次性加载过多数据

总结

Table-Render 提供了强大而灵活的表格渲染能力:

  • 配置化驱动:通过 JSON Schema 快速构建表格
  • 高性能渲染:支持虚拟滚动,轻松处理大数据量
  • 丰富的功能:排序、筛选、分页、导出等完整功能
  • 灵活定制:支持自定义列、主题、样式等

通过合理使用这些特性,可以快速构建出功能完善、性能优异的数据表格组件。

资源下载
下载价格免费
注意:本网站资源属于虚拟产品,不支持退款。请谨慎购买! 购买后资源无法下载,请联系客服QQ:844475003,微信号:th844475003。
原文链接:https://code.ifrontend.net/archives/915,转载请注明出处。
0

评论0

显示验证码
没有账号?注册  忘记密码?