我正在我的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
没有直接方法显示mgr-pdf-viewer-react
的进度%。因此,您必须自己动手做。
ref
并将其附加到PDF
组件。该库维护一个称为pages
的状态,该状态在加载pdf文档后设置。使用pages
读取ref
值并显示进度条,直到页面具有一定值为止。使用一些库作为进度条。我用过react-progressbar
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>
);
}