【问题标题】:How to render images with React-Native-FS如何使用 React-Native-FS 渲染图像
【发布时间】:2019-05-22 20:59:42
【问题描述】:

在我的 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,图像就会存在,它会正确渲染。

【问题讨论】:

    标签: react-native react-native-fs


    【解决方案1】:

    我错过了“file://”

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

    【讨论】:

      【解决方案2】:

      我偶然发现了同样的问题。您还可以将可重用的 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
          }
      })
      

      【讨论】:

        猜你喜欢
        • 2018-03-23
        • 1970-01-01
        • 2020-03-23
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 2019-02-11
        • 2019-11-21
        • 1970-01-01
        相关资源
        最近更新 更多