React项目中react-pdf/renderer的PDFDownloadLink组件JSX内失效问题
It looks like the issue stems from defining the GeneratePdf component inside the render method of your DownloadButton class component. Every time DownloadButton re-renders, React creates a brand new version of GeneratePdf, which causes unnecessary unmounts/mounts and breaks the internal state management of PDFDownloadLink.
Here's how to fix it:
Step 1: Rewrite the DownloadButton Component
Remove the internal GeneratePdf component definition and render PDFDownloadLink directly in the render method. This avoids the component recreation issue:
// DownloadButton.js import React from 'react'; import { PDFDownloadLink } from '@react-pdf/renderer'; import App from './App'; class DownloadButton extends React.Component { render() { return ( <div> <h4> <PDFDownloadLink document={<App />} fileName="somename.pdf" > {({ blob, url, loading, error }) => loading ? 'Loading document...' : 'Download now!' } </PDFDownloadLink> </h4> </div> ); } } export default DownloadButton;
Step 2: Update index.js to Use the Fixed Component
Replace your custom PDF component with the corrected DownloadButton:
// index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import * as serviceWorker from './serviceWorker'; import DownloadButton from './DownloadButton'; ReactDOM.render(<DownloadButton />, document.getElementById('root')); serviceWorker.unregister();
Bonus: Use a Functional Component (Simpler Alternative)
If you prefer, you can rewrite DownloadButton as a functional component for cleaner code:
// DownloadButton.js (functional version) import React from 'react'; import { PDFDownloadLink } from '@react-pdf/renderer'; import App from './App'; const DownloadButton = () => ( <div> <h4> <PDFDownloadLink document={<App />} fileName="somename.pdf" > {({ blob, url, loading, error }) => loading ? 'Loading document...' : 'Download now!' } </PDFDownloadLink> </h4> </div> ); export default DownloadButton;
This should resolve the issue and let your download button work exactly like it did when you used PDFDownloadLink directly in ReactDOM.render.
内容的提问来源于stack exchange,提问作者Shubham

