日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React中使用react-file-viewer問題_React

作者:很好。 ? 更新時間: 2022-10-28 編程語言

使用react-file-viewer

1.npm install react-file-viewer

2.在組建中引入import FileViewer from 'react-file-viewer';

3.使用:

 <FileViewer
    fileType={this.state.imgFlieType}//文件類型
    filePath={this.state.details.dragger}//文件地址
    onError={console.log('錯誤信息')}
    errorComponent={console.log('發生錯誤')}//[可選]:發生錯誤時呈現的組件,而不是react-file- 
     viewer隨附的默認錯誤組件
    unsupportedComponent={console.log('不支持')} //[可選]:在不支持文件格式的情況下呈現的組件
/>

注意:

在使用插件時出現如下報錯時:

原因:react-file-viewer只支持文件網絡地址,本地地址可能不支持

解決辦法:需要把本地地址換成網絡地址進行測試

react-file-viewer預覽本地文件

代碼

import React, {Component} from 'react';
import FileViewer from 'react-file-viewer';
export default class MyComponent extends Component {
    state = {
        fileLocalUrl: null,
        type: ''
    }
    changeFile(e) {
        let file = e.currentTarget.files[0]
        let fileName = file.name
        console.log(file)
        window.URL = window.URL || window.webkitURL;
        this.setState({
            fileLocalUrl: window.URL.createObjectURL(file),
            type: fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)
        })
    }
    render() {
        const {fileLocalUrl, type} = this.state
        return (
            <div>
                {
                    fileLocalUrl && <FileViewer
                        fileType={type}
                        filePath={fileLocalUrl}
                        errorComponent={<div>錯誤</div>}
                        onError={this.onError}/>
                }
                <input type="file" onChange={e => this.changeFile(e)}/>
            </div>
        );
    }
}

能遇到這個問題的大部分都是直接把file丟進組件,導致報錯

解決思路

window.URL.createObjectURL,創建文件對象的URL,將URL丟進組件即可

在移除文件對象URL的時候記得調用URL.revokeObjectURL(url),清理內存,否則會一直存在內存中,詳見官網

https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL

對于大文件可能會導致內存崩潰,切記不要預覽大文件,最好限制在30M以內

原文鏈接:https://blog.csdn.net/qq_52886072/article/details/122622404

欄目分類
最近更新