英文:
Server Error Error: PDFDownloadLink is a web specific API. You're either using this component on Node, or your bundler is not loading react-pdf f
问题
以下是代码的翻译部分:
我已经在Next.js中创建了这个报告卡生成器,但在将其应用到我的项目之前,我尝试使用这个简单的示例来测试`@react-pdf/renderer`。但是我收到了以下错误消息。
`服务器错误
错误:PDFDownloadLink是一个特定于Web的API。您要么在Node上使用此组件,要么您的捆绑器未从适当的Web构建加载react-pdf。`
```javascript
import React from 'react';
// import Report from '@/pages/report/index';
import { PDFDownloadLink, Text, Document, Page } from '@react-pdf/renderer';
const TestComponent = () => {
return (
<Document>
<Page>
<Text>Hello World</Text>
</Page>
</Document>
);
};
export default function ReportGenerator() {
return (
<>
<div>
<PDFDownloadLink document={<TestComponent />} fileName="report.pdf">
下载PDF
</PDFDownloadLink>
<TestComponent />
</div>
</>
);
}
希望这可以帮助您理解代码部分的内容。
英文:
I have created this Report card generator in Next.js, but trying to test @react-pdf/renderer
with this simple example before implement it in my project. Yet I'm receiving this error.
Server Error
Error: PDFDownloadLink is a web specific API. You're either using this component on Node, or your bundler is not loading react-pdf from the appropriate web build.
import React from 'react';
// import Report from '@/pages/report/index';
import { PDFDownloadLink, Text, Document, Page } from '@react-pdf/renderer';
const TestComponent = () => {
return (
<Document>
<Page>
<Text>Hello World</Text>
</Page>
</Document>
);
};
export default function ReportGenerator() {
return (
<>
<div>
<PDFDownloadLink document={<TestComponent />} fileName="report.pdf">
Download PDF
</PDFDownloadLink>
<TestComponent />
</div>
</>
);
}
答案1
得分: 1
Next.js试图在构建时静态呈现PDF,但与PDFDownloadLink不兼容,因为它需要在客户端处理。我通过使用钩子来有条件地在客户端而不是在静态站点构建中呈现它来解决了这个问题。
英文:
Next.js is trying to statically render the PDF at build time which doesn't work with PDFDownloadLink since it needs to be handled client side. I was able to resolve this by using hooks to conditionally render it by the client instead of in the static site build.
export default function ReportGenerator () {
const [isClient, setIsClient] = useState(false)
useEffect(() => {
setIsClient(true)
}, [])
return (
<>
{ isClient ?
<div>
<PDFDownloadLink document={<TestComponent />} fileName="report.pdf">
Download PDF
</PDFDownloadLink>
<TestComponent />
</div>
: null}
</>
)
}
答案2
得分: 0
我遇到了完全相同的错误,并尝试了几种解决方案,但这是最简单且已获 Nextjs 认可的方法。只需在文件顶部包含'use client'
指令。有关更多信息,请查看:https://nextjs.org/docs/getting-started/react-essentials#the-use-client-directive
英文:
I ran into the exact same error, and tried several solutions, but this is the easiest and Nextjs aproved.
Just include the 'use client'
directive in the top of your file.
For more informaton you can check this: https://nextjs.org/docs/getting-started/react-essentials#the-use-client-directive
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论