【问题标题】:React-Native : Download Remote Image to local and use static urlReact-Native:将远程图像下载到本地并使用静态 url
【发布时间】:2018-06-25 10:03:48
【问题描述】:

我正在使用 React-Native 为 Android 开发一个应用程序,它使用 react-native-maps 包。

在标记组件(react-native-maps)中有一个名为“image”的道具,它只能用于本地图像。但在我的情况下,我需要渲染远程图像 Url

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

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

  • 将远程网址下载到图像文件夹。
  • 在标记组件中使用保存的图像 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')}
    />)
}

有什么办法可以做到吗?

我尝试过创建自定义标记,但没有成功。 #issue

【问题讨论】:

    标签: javascript react-native react-native-maps


    【解决方案1】:

    您可以使用 react-native-fs 和路径,如下所示 从“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}
        })
     },
    }
    

    【讨论】:

    • 已解决原生地图获得了包含此修复的新更新,现在我可以在地图中渲染动态图像
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2017-06-05
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多