如何在GatsbyJS中使用Adobe Embed API及解决AdobeDC未定义报错
错误原因
- 核心错误1:你将React专属的
useEffectHook写在了<Helmet>包裹的原生<script>标签中,原生JavaScript上下文无法识别React Hook语法,导致逻辑完全无法正常执行。 - 核心错误2:业务逻辑和组件生命周期没有绑定,SDK加载时机和组件挂载时机不同步,也会导致
AdobeDC未定义的报错。
正确实现步骤
- 首先确保你已经安装了
react-helmet对应的Gatsby插件,如果未安装执行以下命令:
npm install gatsby-plugin-react-helmet react-helmet
- 在项目根目录的
gatsby-config.js的plugins数组中添加插件配置:
module.exports = { plugins: [ // 其他现有插件 `gatsby-plugin-react-helmet` ] }
- 在你需要使用PDF预览功能的页面/组件中编写逻辑,
<Helmet>仅用来引入Adobe SDK脚本,业务逻辑放到组件内部的useEffect中:
import React, { useEffect } from "react" import { Helmet } from "react-helmet" const PdfPreview = () => { useEffect(() => { // 适配Gatsby构建阶段无window对象的场景 if (typeof window === 'undefined') return // 定义SDK加载完成后的处理函数 const loadPdf = () => { const adobeDCView = new window.AdobeDC.View({ clientId: "替换为你自己的CLIENT_ID", // 替换为你的Adobe Client ID }); adobeDCView.previewFile({ content: { location: { url: "替换为你的PDF文件地址", }, }, metaData: { fileName: "替换为你的PDF文件名" } }, { embedMode: "LIGHT_BOX" }); }; // 监听SDK加载完成事件 document.addEventListener("adobe_dc_view_sdk.ready", loadPdf); // 组件卸载时移除事件监听,避免内存泄漏 return () => { document.removeEventListener("adobe_dc_view_sdk.ready", loadPdf); }; }, []); return ( <> <Helmet> <!-- 仅在这里引入Adobe SDK脚本 --> <script src="https://documentcloud.adobe.com/view-sdk/main.js" /> </Helmet> <!-- 你页面的其他内容 --> <div>你的页面内容</div> </> ) } export default PdfPreview
内容的提问来源于stack exchange,提问作者Anilo
相关产品推荐
相关产品推荐

