React - 动态导入pdf文件的路径

React - Import dynamically path to pdf file

首先,我的页面将向 API

发出一个 http 请求

API 然后响应一个具有 path: ./assets/sample.pdf

的对象

我想从 import urlPdf from response.path

得到 urlPdf

我该怎么做?

我会尝试 https://www.npmjs.com/package/react-pdf

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

const App = () => {
  const [pageNumber, setPageNumber] = useState();
  const [numPages, setNumPages] = useState();
  const [urlPdf, setUrlPdf] = useState();

  const _onDocumentLoadSuccess = ({ numPages }) => setNumPages(numPages);
  
  const fetchPdfPath = ({
    // logic handle get path...
    // setUrlPdf(response.data);
  })
  
  return (
    <div>
      {urlPdf && (
        <Document
          file={urlPdf}
          onLoadSuccess={_onDocumentLoadSuccess}
        >
          <Page pageNumber={pageNumber} />
        </Document>
      )}
      <p>Page {pageNumber} of {numPages}</p>
    </div>
  );
}

噢超级简单。刚刚 const result = require(response.path)