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

时间:2018-06-25 10:03:48

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

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

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

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

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

  • 将远程URL下载到images文件夹。
  • 使用标记组件中保存的图像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

1 个答案:

答案 0 :(得分:2)

您可以使用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}
    })
 },
}