You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:10:02