1

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

在反应类中:

state = {source:null}

async componentDidMount() {    

  async loadFile ( path ){
    await this.setState({source:{uri:path}})
  }

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


  await RNFS.exists(path).then( exists => {
        if(exists){
          this.loadFile(path);
      }
 }

   renderItem = ({ item }) => (
      <View key={item.Id} >
        <View>
          <TouchableOpacity onPress={() => this.onPressItem(item)}>
          <Text>{item.cardName}</Text>  
          <Image 
          source={this.state.source}
          style={{ width:'auto', height: 55 }}
          />
          </TouchableOpacity>
        </View>
      </View>
    );

如果我将它转换为 base64,图像就会存在,它会正确渲染。

4

2 回答 2

1

我偶然发现了同样的问题。您还可以将可重用的 Image 组件用于本地图像。如果您只想显示本地 FS 中的图像,请复制 render() 方法。

// ... 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
    }
})
于 2021-02-12T15:36:05.337 回答
1

我错过了“文件://”

const path = "file://"+RNFS.DocumentDirectoryPath+'/images/d88b102c-d4c6-4dc1-9a4c-f2a0e599ddbf.jpg'
于 2019-05-23T07:27:18.873 回答