根据业务需求需要在前端预览多个word、excel、pdf,所以把插件封装成了组件,方便以后使用
@/components/FileViewer/index.js
import React, { useEffect, useState } from 'react'
import NewFileViewer from 'react-file-viewer'
import "./index.less"
export default function FileViewer (props){
const filePath = props.file
const [type, setType] = useState('')
useEffect(() => {
const type = filePath.split('.')[filePath.split('.').length - 1]
setType(type)
}, [filePath])
const getError = (val) => {
console.log('err=', val)
}
return (
<div className='file-view'>
{type ? (
<NewFileViewer
fileType={type}
filePath={filePath}
errorComponent={getError}
onError={err => console.log(err)}
/>
) : (
<div className='file-view-warn'>暂无文件预览</div>
)}
</div>
)
}
@/components/FileViewer/index.less
.file-view{
width: 100%;
height: 100%;
.file-view-warn{
padding-top: 40px;
font-size: 14px;
color: #666;
text-align: center;
}
.pdf-canvas{
text-align: center;
}
}
@/view/useFileViewer/index.js
// 引入组件
import FileViewer from "@/components/FileViewer"
// 使用组件
<FileViewer file={fileUrl}></FileViewer>
问题:
使用过程中,因为要切换文件,出现了同类型文件无法切换的问题。比如原来浏览docx文档,切换另一个docx的时候会出现切换不了的情况(实际上参数已经传过去,但是无法显示),但是从docx切换到excel,又从excel切换到另一个docx就可以正常使用。
解决方法:每个文件都给一个FileViewer,让FileViewer之间切换,而不是修改fileUrl
注:之前想使用className添加 display: block|none 的方式切换,但是第二个文件block之后却无法正常加载显示,所以使用了另一种方法
// 给每个文件一个FileViewer,根据选中fileUrl渲染
{
fileArr.map(item => item.fileUrl === fileUrl ? (<FileViewer file={item.longUrl}></FileViewer>):null)
}
还有一个大问题,excel文件的宽如果太长会出现无法显示完整的情况,有大佬有解决方法吗TvT?
excel暂时还未使用其他插件,如果有解决方法会接着更新