簡體   English   中英

有沒有辦法使用 Next.js 動態導入來導入函數? Next.js ssr 的 react-component-export-image 問題

[英]Is there a way to import a function using Next.js dynamic import? react-component-export-image issues with Next.js ssr

導入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

next/dynamic用於動態導入 React 組件,而不是常規的 JavaScript 函數或庫。

為此,您可以在onClick回調中對exportComponentAsPNG使用常規動態導入。

<button onClick={async () => {
    const { exportComponentAsPNG } = await import('react-component-export-image')
    exportComponentAsPNG(componentRef)
}}>

exportComponentAsPNG函數需要訪問服務器端渲染未定義的window 通過將使用exportComponentAsPNGPlaque組件動態導入到調用它的頁面,服務器端渲染設置為“false”,我能夠解決該問題。

import dynamic from 'next/dynamic'

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

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

export default Page

現在組件不再使用 SSR,我可以正常導入和使用該功能。

import { exportComponentAsPNG } from 'react-component-export-image'

您可以在這里找到該庫的文檔: https : //www.npmjs.com/package/react-component-export-image

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM