繁体   English   中英

React-Native:将远程图像下载到本地并使用静态URL

[英]React-Native : Download Remote Image to local and use static url

我正在使用React-Native开发适用于Android的应用,该应用使用react-native-maps包。

在标记组件(react-native-maps)中,有一个名为“ image”的道具,该道具只能与本地图像一起使用。 但就我而言,我需要渲染远程图像网址

<Marker
  coordinate={marker.latlng}
  image={require('../images/pin.png')}
/>

上面的代码可以正常工作,因为图像是静态的,但是我需要渲染一个远程图像而不是pin.jpg,所以有办法我可以做到这一点。

  • 将远程URL下载到图像文件夹。
  • 使用标记组件中保存的图像uri。

这是我想要达到的目标-类似于下面的代码

let path_to_save_image = '../images/'
some_package.fetch('http://www.example.com/image/new_image.png', 
    path_to_save_image, {
    //some headers ..
    })
    .then((res) => {
    console.log('The file saved ')
    })


render (){
  return (
    <Marker
     coordinate={marker.latlng}
    image={require('../images/new_image.png')}
    />)
}

有没有办法我可以做到这一点?

我尝试创建自定义标记,但无法解决。 #问题

您可以使用react-native-fs和path,如下所示,从'react-native-fs'导入RNFS;

module.exports = {
  getFileName(name: string) {
    const FILE = Platform.OS === 'ios' ? '' : 'file://' ;
    return FILE + RNFS.DocumentDirectoryPath + '/' + name + '.png';
  },

  downloadAndGetImageUrl(name: string, source_url: string) {
    let fileName = this.getFileName(name);
    return RNFS.exists(fileName)
     .then(response => {
       if(response) {
         return {uri: fileName}
       }else {
         let destination_path = '/' + name + '.jpg';
         return RNFS.downloadFile({
           fromUrl: source_url,
           toFile: RNFS.DocumentDirectoryPath + destination_path
         }).promise.then(response => {
            return {uri: fileName}
         }).catch((error) => {
           return {uri:source_url}
        });
      }
    })
    .catch((error) => {
      return {uri: source_url}
    })
 },
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM