【问题标题】:how to show loading in percent, while loading from src folder如何在从 src 文件夹加载时以百分比显示加载
【发布时间】:2020-09-26 10:53:00
【问题描述】:

我正在我的 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】:

    mgr-pdf-viewer-react 没有直接的方式来显示进度百分比。所以你必须自己做。

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

    使用一些库作为进度条。我用过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>
      );
    }
    
    

    【讨论】:

    • 您好,感谢您的建议。它确实有效。但是还有更好的方法,也许不用mgr-pdf-viewer-react,我愿意用别的阅读器没问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2013-05-17
    • 2014-04-25
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多