有没有办法使用 Next.js 动态导入来导入函数?Next.js ssr 的反应组件导出图像问题

Col*_*ole 5 javascript reactjs next.js

导入时出现“窗口未定义”错误,react-component-export-image因此我使用动态导入来解决该问题。我不再收到该错误,但现在我收到“exportComponentAsPNG(componentRef)不是函数”。有没有更好的方法来处理“窗口未定义”错误或使用我动态导入的函数的方法?如果没有,是否有不同的 npm 库可以从 React 组件生成图像?

import React, { useRef } from 'react'
// import { exportComponentAsPNG } from 'react-component-export-image' *This gave window not defined error so I used dynamic import*
import dynamic from 'next/dynamic'
import ProductCard from '../ProductCard/ProductCard.component'
import Button from '../Button/Button.component'

const { exportComponentAsPNG } = dynamic(
  () => import('react-component-export-image'),
  {
    ssr: false
  }
)

const Plaque = () => {
 const componentRef = useRef()

  // eslint-disable-next-line react/display-name
  const ComponentToPrint = React.forwardRef((props, ref) => {
    return (
      <div ref={ref}>
        <ProductCard />
      </div>
    )
  })

  return (
        <ComponentToPrint ref={componentRef} />
          <button onClick={() => exportComponentAsPNG(componentRef)}> // "Error: exportComponentAsPNG is not a function"
          Export As PNG
        </button>
  )
}

export default Plaque
Run Code Online (Sandbox Code Playgroud)

Col*_*ole 4

exportComponentAsPNG函数需要访问window服务器端渲染未定义的内容。我能够通过动态导入用于调用该页面Plaque的组件exportComponentAsPNG并将服务器端渲染设置为“false”来解决该问题。

import dynamic from 'next/dynamic'

const Plaque = dynamic(() => import('../compnonents/Plaque'), {
  ssr: false
})

const Page = () => {
  return <Plaque />
}

export default Page
Run Code Online (Sandbox Code Playgroud)

现在该组件不再使用 SSR,我可以正常导入和使用该函数。

import { exportComponentAsPNG } from 'react-component-export-image'
Run Code Online (Sandbox Code Playgroud)

在这里您可以找到该库的文档:https://www.npmjs.com/package/react-component-export-image