如何使用React-Native-FS渲染图像

时间:2019-05-22 20:59:43

标签: react-native react-native-fs

在我的Android react-native应用程序中,我将jpg文件从缓存文件夹移动到RNFS.DocumentDirectoryPath中,在其中创建了“图像”文件夹。我无法渲染这些图像:

在React类中:

function start() {
    gapi.client.init({
      'apiKey': '[MY_API_KEY]',
      'discoveryDocs': ['https://dialogflow.googleapis.com/$discovery/rest?version=v2beta1'],
    }).then(function() {
      // Do stuff
    })
};

gapi.load('client', start);

如果我将其转换为base64,则该图像将正确呈现。

2 个答案:

答案 0 :(得分:0)

我缺少“ file://”

const path = "file://"+RNFS.DocumentDirectoryPath+'/images/d88b102c-d4c6-4dc1-9a4c-f2a0e599ddbf.jpg'

答案 1 :(得分:0)

我偶然发现了同样的问题。您还可以对本地图像使用可重用的 Image 组件。如果你只是想显示来自本地FS的图片,复制render()-Method。

// ... Any part of your application: <FSImageView {...new FSImage("imageToDisplay.png")} /> 

// UI-Model
export class FSImage  {    

    // just an example: size, filepath... whatever you need
    private imageName: string 

    constructor(imageName: string){
        this.imageName = imageName
    }
}

export class FSImageView extends React.Component<FSImage, null> {
    
    render(){
        
        const RNFS = require('react-native-fs') // https://github.com/itinance/react-native-fs#readme (npm install react-native-fs)
        const platformFilePath = Platform.OS === 'android' ? RNFS.DocumentDirectoryPath : RNFS.MainBundlePath;
        const filePath = "file://" + platformFilePath + "/" + this.props.imageName

        return(
             <Image style={fsImageViewStyles.imageSize} source={{uri:filePath}} />  // setting the size is necessary otherwise it won't be displayed
        )
    }
}

const fsImageViewStyles = StyleSheet.create({
    imageSize : {
        width: 90,
        height: 90
    }
})