react-pdf 库中的 PDFDownloadLink 当有人点击时下载 pdf。 我想根据某些条件通过代码触发此点击事件。 如何通过代码显式调用PDFDownloadLink的点击?
有点晚了,但是您可以将
ref
传递给渲染函数的返回值,并使用它来强制调用 click()
。为此,您需要使用单独的组件包装器:
const DownloadLink = memo(function () {
const linkRef = useRef(null)
const onLoadingFinished = useCallback(function () {
// When this function is called the first time it is safe to initiate the download
const elem = linkRef?.current
if (elem !== null) {
elem.click()
}
}, [])
return (
<PDFDownloadLink document={<MyDoc />} fileName={'my-file.pdf'}>
{({ blob, url, loading, error }) => (
// You shouldn't call setState() here, so we need to use a separate component to keep track of whether the document has finished rendering
<WorkaroundContainer ref={linkRef} loading={loading} onLoadingFinished={onLoadingFinished} />
)}
</PDFDownloadLink>
)
})
const WorkaroundContainer = forwardRef(function ({ loading, onLoadingFinished }, ref) {
useEffect(() => {
if (!loading) {
onLoadingFinished()
}
}, [loading])
// If you only want to initiate the download imperatively, hide the element via CSS (e.g. `visibility: hidden`)
return (
<div ref={ref}>
{loading ? 'Loading...' : 'Download PDF'}
</div>
)
})
<PDFDownloadLink document={< yourPDFComponent/>}>
// the download button has to be hidden
<p ref={downloadRef} className={"hidden"}>Download buttton</p>
</PDFDownloadLink>
// inside the function you want to call the event, just call the click like this:
downloadRef.current.click() // your file will be downloaded, bye