【React】React预览docx文件

React预览docx文件

封装DocxView组件,用于显示docx文件的预览,支持加载loading效果

安装依赖

npm i docx-preview
import React, { useEffect, useRef, useState } from 'react'
import * as docx from 'docx-preview'
import { Spin } from 'antd'
import { askDocApiUrls } from 'src/shared/url-map'

export interface Props {
  fileInfo: string
}

const DocxView = (props: Props) => {
  const { fileInfo } = props
  const [isLoading, setIsLoading] = useState(true)
  const docxContainerRef = useRef(null)

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(fileInfo)
        const data = await response.blob()
        const containerElement = docxContainerRef.current
        if (containerElement) {
          docx.renderAsync(data, containerElement).then(() => {
            console.info('docx: finished')
            setIsLoading(false)
          })
        }
      } catch (error) {
        setIsLoading(false)
        console.error('Error fetching or rendering document:', error)
      }
    }

    fetchData()
  }, [fileInfo])

  return (
    
{isLoading && (
)}
) } export default DocxView

你可能感兴趣的:(react.js,javascript,ecmascript)