react-native项目要求实现word,excel,pdf,mp4,png等格式附件图片的在线预览,最终选用react-native-doc-viewer实现,

具体步骤如下:

1、安装react-native-doc-viewer

      (1) npm install react-native-doc-viewer --save

      (2) react-native link react-native-doc-viewer

2、修改源代码

    (1) 因为react-native-doc-viewer已经很久没有更新了,所以SdkVersion是23,比较低,将它修改成如下图所示:

(2)找到下图中左侧的文件,将右侧红圈圈里面的代码注释掉

至此,所以安装和配置完成,下面是写代码步骤

3、代码实现

 

import OpenFile from 'react-native-doc-viewer';
//预览附件
viewAttachment(attachment) {
   let fileTypeArr = ['xls', 'ppt', 'doc', 'xlsx', 'pptx', 'docx', 'png', 'jpg', 'pdf', 'mp4', 'txt'];
   if (fileTypeArr.indexOf(attachment.fileSuffix) >= 0) {
      if (Platform.OS === 'ios') {
         OpenFile.openDoc([{
            url: attachment.filePath,
            fileNameOptional: attachment.fileName
         }], (error, url) => {
            if (error) {
               console.log(error);
            } else {
               console.log(url)
            }
         })
      } else {
         OpenFile.openDoc([{
            url: attachment.filePath, 
            fileName: attachment.fileName,
            cache: false,
            fileType: attachment.fileSuffix
         }], (error, url) => {
            if (error) {
               console.error(error);
            } else {
               console.log(url)
            }
         });
      }
   } else {
      Toast.show('app端暂不支持此种格式附件预览,请去pc端预览');
   }
}

应用会打开手机上对应的第三方软件,做预览。 

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐