首页 > 解决方案 > Uncaught TypeError: parentInstance.children.push is not a function error in react-pdf/renderer in Next.js

问题描述

我正在尝试在 Next.js 应用程序的屏幕上打印 pdf。我正在使用 Next.js 文档中的自定义文档来操作 DOM。自定义文档的链接: https ://nextjs.org/docs/advanced-features/custom-document 我的文档与此自定义文档相同,只是我像这样包含了我的 DOM id,它写在以下<NextScript/>行旁边: <div id="my-pdf"></div> 下面是我使用 createPortal 编写我的 pdf 的文件:

import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";

// Create Document Component
export default function TestDoc({ show, children }) {
  const [isBrowser, setIsBrowser] = useState(false);
  useEffect(() => setIsBrowser(true), []);
  const paperContent = show ? <div>{children}</div> : null;

  if (isBrowser) {
    return ReactDOM.createPortal(
      paperContent,
      document.getElementById("my-pdf")
    );
  } else {
    return null;
  }
}

下面是我要渲染的 children 道具的代码:

import TestDoc from "@/components/TestDoc";
import {
  Document,
  Page,
  Text,
  View,
  StyleSheet,
  PDFViewer,
} from "@react-pdf/renderer";
export default function Component(){

...code...

return(
{showPaper && (
        <PDFViewer>
          <TestDoc show={showPaper}>
            <Document>
              <Page size="A4" style={styles.page}>
                <View style={styles.section}>
                  <Text>Section #1</Text>
                </View>
                <View style={styles.section}>
                  <Text>Section #2</Text>
                </View>
              </Page>
            </Document>
          </TestDoc>
        </PDFViewer>
      )}
   );
}

但是当我运行这段代码时,它会产生这些错误:

1)

Uncaught TypeError: parentInstance.children.push is not a function
    at appendChildToContainer...
  1. 未捕获的类型错误:_parentInstance$child3.indexOf 不是 removeChildFromContainer 中的函数...

  2. 上述错误发生在组件中: in div (at TestDoc.js:9) in TestDoc (at contact.js:74) 考虑在树中添加错误边界以自​​定义错误处理行为。

  3. 未捕获的 TypeError:parentInstance.children.push 不是 appendChildToContainer 中的函数

  4. The above error occurred in the <PDFViewer> component: at PDFViewer...

  5. 上述错误发生在组件中:在 TestDoc (at contact.js:74) 考虑向树中添加错误边界以自​​定义错误处理行为。

我花了几个小时来修复它,但无法解决它。请帮我解决这个问题,我需要让 react-pdf/renderer 在我的 Next.JS 应用程序中工作。

我将衷心感谢您的帮助。

标签: javascriptreactjspdfnext.jsreact-pdf

解决方案


推荐阅读