使用react-pdf无法生成PDF下载链接,页面无内容显示求助
React+Vite+Tailwind 中 react-pdf 无内容显示的问题解决
你代码的核心问题是PDFDownloadLink 的渲染回调函数存在语法错误,导致组件无法正常解析渲染,页面无内容输出。
具体错误点
你的 PDFDownloadLink 回调里缺少了 loading 状态的判断逻辑,且括号不匹配:
// 错误代码片段 {({ blob, url, loading, error }) => <button className=" bg-slate-500">Loading document...</button> ) : ( <button className=" bg-slate-500">Download now!</button> ) }
这里没有开头的 loading ? 条件,属于不完整的三元表达式,JSX 无法正常编译。
修正后的完整代码
import { Document, Page, PDFDownloadLink, StyleSheet, Text, View } from "@react-pdf/renderer"; import React from "react"; // Create styles const styles = StyleSheet.create({ page: { flexDirection: "row", backgroundColor: "#E4E4E4", }, section: { margin: 10, padding: 10, flexGrow: 1, }, }); // Create Document Component const MyDoc = () => ( <Document> <Page size="A4" style={styles.page}> <View style={styles.section}> <Text>Section #1</Text> </View> <View style={styles.section}> <Text>Section #2</Text> </View> </Page> </Document> ); const Dashboard = () => ( <div> <PDFDownloadLink className="bg-slate-600 p-2 rounded" document={<MyDoc />} fileName="somename.pdf" > {({ loading, error }) => { // 处理错误状态 if (error) return <button className="bg-red-500 text-white p-2 rounded">生成失败</button>; // 根据loading状态显示不同内容 return loading ? ( <button className="bg-slate-500 text-white p-2 rounded">Loading document...</button> ) : ( <button className="bg-slate-500 text-white p-2 rounded">Download now!</button> ); }} </PDFDownloadLink> </div> ); export default Dashboard;
额外检查项
- 确认已经正确安装依赖:
npm install @react-pdf/renderer
- Vite 环境下无需额外配置,
@react-pdf/renderer已兼容 Vite 打包工具。
修正后,页面会正常显示下载按钮,点击即可生成并下载指定的PDF文件。
内容的提问来源于stack exchange,提问作者Nabila Shafa
相关产品推荐
相关产品推荐

