簡體   English   中英

如何在 Typescript 中使用 react-pdf 庫

[英]How to use react-pdf library with Typescript

我正在嘗試使用一個 npm 庫來幫助我呈現 pdf 文檔。 我找到了 react-pdf 但它還沒有 TypeScript 的類型,所以我正在使用它,如下所示:

let Document = require('react-pdf');
let Page = require('react-pdf');

class PdfViewer extends React.Component<PdfViewer.Props, PdfViewer.State> {

  constructor(props: PdfViewer.Props) {
    super(props);
    this.state = {
      numPages: null,
      pageNumber: 1,
    };

  }
  onDocumentLoadSuccess = ( numPages: number ) => {
    this.setState({ numPages });

  }

  componentWillReceiveProps(nextProps: PdfViewer.Props) {
    // this.setState(CsvViewer.parse(nextProps.data));
  }

  render() {
      const {url} = this.props;
      const { pageNumber, numPages } = this.state;

      const buffer = data as ArrayBuffer;

      return ( 
      <div>
        <Document
          file={url}
          onLoadSuccess={this.onDocumentLoadSuccess}
        >
          <Page pageNumber={pageNumber} />
        </Document>
        <p>Page {pageNumber} of {numPages}</p>
      </div>
      );

  }
}

但它拋出了這個錯誤:

元素類型無效:應為字符串(用於內置組件)或類/函數(用於復合組件)但得到:對象。

我在 GitHub 上找到了這個,但對我幫助不大。 我去了圖書館的文檔,我在文件參數中傳遞了一個對象,就像他們展示的那樣,但同樣的錯誤。 我認為是另外一回事。 我去了react-pdf庫的源代碼,我認為這是他們用來從參數中獲取文件的函數:

findDocumentSource = async () => {
    const { file } = this.props;

    if (!file) {
      return null;
    }

    // File is a string
    if (typeof file === 'string') {
      if (isDataURI(file)) {
        const fileUint8Array = dataURItoUint8Array(file);
        return { data: fileUint8Array };
      }

      displayCORSWarning();
      return { url: file };
    }

    // File is PDFDataRangeTransport
    if (file instanceof PDFDataRangeTransport) {
      return { range: file };
    }

    // File is an ArrayBuffer
    if (isArrayBuffer(file)) {
      return { data: file };
    }

    /**
     * The cases below are browser-only.
     * If you're running on a non-browser environment, these cases will be of no use.
     */
    if (isBrowser) {
      // File is a Blob
      if (isBlob(file) || isFile(file)) {
        return { data: await loadFromFile(file) };
      }
    }

    // At this point, file must be an object
    if (typeof file !== 'object') {
      throw new Error('Invalid parameter in file, need either Uint8Array, string or a parameter object');
    }

    if (!file.url && !file.data && !file.range) {
      throw new Error('Invalid parameter object: need either .data, .range or .url');
    }

    // File .url is a string
    if (typeof file.url === 'string') {
      if (isDataURI(file.url)) {
        const { url, ...otherParams } = file;
        const fileUint8Array = dataURItoUint8Array(url);
        return { data: fileUint8Array, ...otherParams };
      }

      displayCORSWarning();
    }

    return file;
  };

但我懷疑錯誤就在這里,但我不知道可能是什么。 我使用的react版本是 16.8.2 和 4.0.2 for react-pdf

這是不正確的:

let Document = require('react-pdf');
let Page = require('react-pdf');

執行此操作時,您正在導入整個模塊。 這意味着DocumentPage都包含react-pdf的所有模塊。 相反,您想要做的是導入 ReactPDF 並引用這些模塊:

const ReactPDF = require('react-pdf');

<ReactPDF.Document />
<ReactPDF.Page />

或者你可以使用解構:

import { Document, Page } from 'react-pdf';

//or

const { Document, Page } = require('react-pdf'); 

如果 TypeScript 抱怨缺少聲明,只需將@types文件夾添加到您的項目中,在其中創建一個名為react-pdf的子文件夾,並在該文件夾中創建一個名為index.d.ts的文件,其中包含一行:

declare module "react-pdf"
  • 首先添加類型
  • 如果您使用的是創建反應應用程序,您應該添加:
import { Document, Page, pdfjs } from "react-pdf/dist/esm/entry.webpack";
pdfjs.GlobalWorkerOptions.workerSrc =`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM