如何在React函数式组件中实现Syncfusion Grid的pdfExport功能
报错根因
抛出grid.pdfExport is not a function只有两类核心原因:
- 未引入、未注册PDF导出对应的模块服务,Grid实例上根本没有挂载这个方法
- 函数组件中获取Grid实例的ref写法错误,拿到的不是真实的组件实例
函数式组件正确实现步骤
- 第一步:引入必要依赖
所有导出能力依赖对应模块,缺引就会找不到方法,需要引入的核心内容如下:
import { GridComponent, ColumnsDirective, ColumnDirective, Inject, PdfExport, Toolbar } from '@syncfusion/ej2-react-grids'; import { PdfExportProperties } from '@syncfusion/ej2-grids'; import { useRef, useState } from 'react';
- 第二步:用
useRef正确持有Grid实例
函数组件禁止使用字符串ref,必须通过useRef创建ref对象,绑定到GridComponent的ref属性,调用方法时通过ref.current访问实例。 - 第三步:开启导出配置、注入服务
必须给Grid组件设置allowPdfExport={true},同时通过<Inject>标签注入PdfExport服务,少这步哪怕引了包,实例上也不会挂载导出方法。
可直接运行的完整示例代码
// 测试用示例数据 const gridData = [ { OrderID: 10248, CustomerID: 'VINET', Freight: 32.38, OrderDate: '1996-07-02' }, { OrderID: 10249, CustomerID: 'TOMSP', Freight: 11.61, OrderDate: '1996-07-03' }, { OrderID: 10250, CustomerID: 'HANAR', Freight: 65.83, OrderDate: '1996-07-04' } ]; function PdfExportGrid() { // 创建ref存储Grid实例 const gridRef = useRef(null); const [toolbarOptions] = useState(['PdfExport']); // 工具栏点击触发导出 const toolbarClick = (args) => { if (args.item.id.includes('pdfexport')) { // 可自定义导出配置 const exportProperties = { fileName: '业务数据导出.pdf' }; // 必须通过ref.current访问实例方法 gridRef.current.pdfExport(exportProperties); } } return ( <GridComponent ref={gridRef} dataSource={gridData} allowPdfExport={true} toolbar={toolbarOptions} toolbarClick={toolbarClick} height='350' > <ColumnsDirective> <ColumnDirective field='OrderID' headerText='订单ID' width='120' textAlign='Right'/> <ColumnDirective field='CustomerID' headerText='客户ID' width='150'/> <ColumnDirective field='Freight' headerText='运费' width='120' format='C2' textAlign='Right'/> <ColumnDirective field='OrderDate' headerText='下单日期' width='150' format='yMd'/> </ColumnsDirective> {/* 重点:必须注入PdfExport服务,否则实例不会挂载pdfExport方法 */} <Inject services={[Toolbar, PdfExport]} /> </GridComponent> ) } export default PdfExportGrid;
踩坑排查清单
如果按上面写完还是报错,逐一核对:
- 本地安装的所有
@syncfusion/ej2-*包版本号完全一致,跨大版本混装会导致方法挂载异常 - ref绑定写法正确:直接给Grid传
ref={gridRef},不要写成ref={gridRef.current} - 调用
pdfExport()的时机在Grid挂载完成之后,不要在组件首渲染执行逻辑里直接调用,放在按钮点击、事件回调里调用是安全的 - 不要遗漏
<Inject services={[PdfExport]} />注入代码,这是类组件转函数组件时最高发的漏配项
内容的提问来源于stack exchange,提问作者Arko
相关产品推荐
相关产品推荐

