如何显示从src文件夹加载时的加载百分比

问题描述 投票:0回答:1

我正在我的reactJS应用程序中使用pdf阅读器。我需要显示pdf文件的加载指示器。我的pdf阅读器仅在文件完全加载后才加载。如您在this link中看到的。

我认为先显示单独的加载百分比指示器,然后再加载单独的pdf文件,然后再仅加载pdf加载器组件才能解决问题。

还有一个useState来设置加载状态和加载百分比可能是个好主意。请帮助我实现这一点,并随时提出其他建议。

我当前的代码如下:

import PDFViewer from "mgr-pdf-viewer-react"

function Reader({ bookDetail }) {
    const readerRef = useRef(null)

    return (
        bookDetail !== null && (
            //  ...
                <PDFViewer
                    page={1}
                    document={{
                        url: bookDetail.bookUrl,
                    }}
                />
            // ...
        )
    )
}

export default Reader


javascript reactjs pdf state loader
1个回答
0
投票

没有直接方法显示mgr-pdf-viewer-react的进度%。因此,您必须自己动手做。

  • 使用ref并将其附加到PDF组件。该库维护一个称为pages的状态,该状态在加载pdf文档后设置。使用pages读取ref值并显示进度条,直到页面具有一定值为止。

使用一些库作为进度条。我用过react-progressbar

Working demo

import PDFViewer from "mgr-pdf-viewer-react";
import ProgressBar from "react-progressbar";

export default function App() {
  const [currentProgress, setCurrentProgress] = useState(0);

  useEffect(() => {
    progress();
  }, []);

  const ref = useRef(null);

  const progress = () => {
    let step = 5; // the smaller this is the slower the progress bar
    let current_progress = 0;
    const interval = setInterval(function() {
      current_progress += step;
      setCurrentProgress(current_progress);
      let progress =
        Math.round((Math.atan(current_progress) / (Math.PI / 2)) * 100 * 1000) /
        1000;

      // console.log(ref.current);
      if (ref.current && ref.current.state.pages) {
        console.log("cleared");
        current_progress = 100;
        setCurrentProgress(current_progress);
        clearInterval(interval);
      } else if (progress >= 70) {
        step = 0.1;
      }
    }, 100);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <p>{currentProgress + " %"}</p>
      {<ProgressBar completed={currentProgress} />}
      <PDFViewer
        ref={ref}
        document={{
          url: "https://arxiv.org/pdf/quant-ph/0410100.pdf"
        }}
        // loader={<h2 style={{ color: "#fa5b35" }}>Custom loader element</h2>}
        // loader={<ProgressBar completed={currentProgress} />}
      />
    </div>
  );
}

© www.soinside.com 2019 - 2024. All rights reserved.