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<boolean>(true)
const docxContainerRef = useRef<HTMLDivElement | null>(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 (
<div className="relative h-full">
<div ref={docxContainerRef} className="h-full" />
{isLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-75">
<Spin size="large" />
</div>
)}
</div>
)
}
export default DocxView