【问题标题】:How to use html2canvas with nextjs如何在 nextjs 中使用 html2canvas
【发布时间】:2019-12-30 10:40:47
【问题描述】:

我在 nextjs 中使用html2canvas。由于 nextjs 进行服务器端渲染,因此很难在 nextjs 中使用 html2canvas
我使用nextjs提供的dynamic库导入html2canvas,现在不知道如何使用html2canvas文档中写的导入后的html2canvas函数。

导入 html2canvas

const html2canvas = dynamic(() => import('html2canvas'),{ssr:false})

当我按照文档中所写的步骤运行时,错误输出显示

“html2canvas 不是函数”

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

我想知道如何使用它。

【问题讨论】:

  • html2canvas/dist/html2canvas.js 这个路径是否存在?你在哪里调用 html2canvas(document.body).then(function(canvas) { } 方法
  • 我将路径更改为仅“html2canvas”,并且在函数中使用 html2canvas。

标签: reactjs frontend next.js html2canvas


【解决方案1】:

Nextjs 动态导入用于导入 react 组件。如果你想导入一个节点模块,你可以使用普通的基于 javascript 的动态导入,如下所示

import('html2canvas').then(html2canvas => {
  html2canvas.default(document.body).then(canvas => 
    document.body.appendChild(canvas)
  )
}).catch(e => {console("load failed")})

【讨论】:

  • 谢谢,这个方法有效,我将使用异步等待它。
猜你喜欢
  • 2018-08-29
  • 1970-01-01
  • 2019-07-18
  • 2021-04-20
  • 2022-12-09
  • 2012-04-07
  • 2021-08-10
  • 2021-09-17
  • 2021-08-01
相关资源
最近更新 更多