@1602/react-native-cached-image 中文文档教程

发布于 5年前 浏览 18 项目主页 更新于 3年前

react-native-cached-image

react-native 的 CachedImage 组件

这个包的灵感来自 @jayesbe 的惊人 react-native-cacheable-image 但添加了一些我们在尝试在我们的 react-native 应用程序中处理缓存图像时缺少的功能。

Installation

npm install react-native-cached-image --save
- or -
yarn add react-native-cached-image

我们使用 rn-fetch-blob 来处理这个包中的文件系统访问并且在安装过程中需要一个额外的步骤。

您只需执行一次。

react-native link rn-fetch-blob

或者,如果您想自动将 Android 权限添加到 AndroidManifest.xml,请使用以下代码:将以

RNFB_ANDROID_PERMISSIONS=true react-native link rn-fetch-blob

Network Status - Android only

下行添加到您的 android/app/src/AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Usage

TODO - 添加用法示例

import React from 'react';
import {
    CachedImage,
    ImageCacheProvider
} from 'react-native-cached-image';

const images = [
    'https://example.com/images/1.jpg',
    'https://example.com/images/2.jpg',
    'https://example.com/images/3.jpg',
    // ...
];

export default class Example extends React.Component {
    render() {
        return (
            <ImageCacheProvider
                urlsToPreload={images}
                onPreloadComplete={() => console.log('hey there')}>

                <CachedImage source={{uri: images[0]}}/>

                <CachedImage source={{uri: images[1]}}/>

                <CachedImage source={{uri: images[2]}}/>

            </ImageCacheProvider>
        );
    }
}

API

这个包公开了 3 个模块:

const {
    CachedImage,            // react-native component that is a drop-in replacement for your react-native `Image` components
    ImageCacheProvider,     // a top level component that provides accsess to the underlying `ImageCacheManager` and preloads images
    ImageCacheManager,      // the logic behind cache machanism - ttl, fs, url resolving etc.
} = require('react-native-cached-image');

ImageCacheManager

这是所有缓存魔术发生的地方。 API 通常采用一个 URL 和一组 ImageCacheManagerOptions

ImageCacheManager.downloadAndCacheUrl(url: String, options: ImageCacheManagerOptions): Promise<String>

检查 URL 的缓存(根据 ImageCacheManagerOptions.useQueryParamsInCacheKey 删除固定查询字符串后)。 如果 URL 存在于缓存中且未过期,则使用本地缓存文件路径进行解析。 否则,将文件下载到缓存文件夹中,添加到缓存中,然后返回缓存的文件路径。

ImageCacheManager.seedAndCacheUrl(url: String, seedPath: String, options: ImageCacheManagerOptions): Promise<String>

检查 URL 的缓存(根据 ImageCacheManagerOptions.useQueryParamsInCacheKey 删除固定查询字符串后)。 如果 URL 存在于缓存中且未过期,则使用本地缓存文件路径进行解析。 否则,将种子文件复制到缓存文件夹中,添加到缓存中,然后返回缓存文件路径。

ImageCacheManager.deleteUrl(url: String, options: ImageCacheManagerOptions): Promise

删除 URL 的缓存条目和与其对应的本地文件(如果存在)。

ImageCacheManager.clearCache(options: ImageCacheManagerOptions): Promise

清除 URL 缓存并删除缓存文件夹中的文件(如 ImageCacheManagerOptions.cacheLocation 中所述)

ImageCacheManager.getCacheInfo(options: ImageCacheManagerOptions): Promise.<{file: Array, size: Number}>

返回有关缓存的信息、文件列表和缓存的总大小。

CachedImage

CachedImageImage 组件的替代品,它将尝试缓存远程 URL 以获得更好的性能。
它的主要用途是对用户隐藏缓存层,并提供一种简单的方式来缓存图像。
CachedImage 使用 ImageCacheManager 的实例与缓存交互,如果有 ImageCacheProvider 通过上下文提供的实例,将使用它,否则将使用组件道具中的选项创建一个新实例。

<CachedImage
    source={{
        uri: 'https://example.com/path/to/your/image.jpg'
    }}
    style={styles.image}
/>
Props
  • renderImage - a function that returns a component, used to override the underlying Image component.
  • activityIndicatorProps - props for the ActivityIndicator that is shown while the image is downloaded.
  • defaultSource - prop to display a background image while the source image is downloaded. This will work even in android, but will not display background image if there you set borderRadius on this component style prop
  • loadingIndicator - component prop to set custom ActivityIndicator.
  • fallbackSource - prop to set placeholder image. when source.uri is null or cached failed, the fallbackSource will be display.
  • any of the ImageCacheManagerOptionsPropTypes props - customize the ImageCacheManager for this specific CachedImage instance.

ImageCacheProvider

这是一个具有 2 个主要功能的顶级组件:

  1. Provide the customized ImageCacheManager to nested CachedImage.
  2. Preload a set of URLs.
Props
  • urlsToPreload - an array of URLs to preload when the component mounts. default []
  • numberOfConcurrentPreloads - control the number of concurrent downloads, usually used when the urlsToPreload array is very big. default urlsToPreload.length
  • onPreloadComplete - callback for when the preload is complete and all images are cached.

ImageCacheManagerOptions

一组提供给 ImageCacheManager 的选项,并提供根据您的需要对其进行自定义的方法。

type ImageCacheManagerOptions = {
    headers: PropTypes.object,                      // an object to be used as the headers when sending the request for the url. default {}

    ttl: PropTypes.number,                          // the number of seconds each url will stay in the cache. default 2 weeks

    useQueryParamsInCacheKey: PropTypes.oneOfType([ // when handling a URL with query params, this indicates how it should be treated:
        PropTypes.bool,                             // if a bool value is given the whole query string will be used / ignored
        PropTypes.arrayOf(PropTypes.string)         // if an array of strings is given, only these keys will be taken from the query string.
    ]),                                             // default false

    cacheLocation: PropTypes.string,                // the path to the root of the cache folder. default the device cache dir

    allowSelfSignedSSL: PropTypes.bool,             // true to allow self signed SSL URLs to be downloaded. default false
};

Contributing

请阅读 CONTRIBUTING.md,详细了解我们的行为准则以及向我们提交拉取请求的流程。

react-native-cached-image

CachedImage component for react-native

This package is greatly inspired by @jayesbe's amazing react-native-cacheable-image but adds some functionality that we were missing when trying to handle caching images in our react-native app.

Installation

npm install react-native-cached-image --save
- or -
yarn add react-native-cached-image

We use rn-fetch-blob to handle file system access in this package and it requires an extra step during the installation.

You should only have to do this once.

react-native link rn-fetch-blob

Or, if you want to add Android permissions to AndroidManifest.xml automatically, use this one:

RNFB_ANDROID_PERMISSIONS=true react-native link rn-fetch-blob

Network Status - Android only

Add the following line to your android/app/src/AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Usage

TODO - add usage example

import React from 'react';
import {
    CachedImage,
    ImageCacheProvider
} from 'react-native-cached-image';

const images = [
    'https://example.com/images/1.jpg',
    'https://example.com/images/2.jpg',
    'https://example.com/images/3.jpg',
    // ...
];

export default class Example extends React.Component {
    render() {
        return (
            <ImageCacheProvider
                urlsToPreload={images}
                onPreloadComplete={() => console.log('hey there')}>

                <CachedImage source={{uri: images[0]}}/>

                <CachedImage source={{uri: images[1]}}/>

                <CachedImage source={{uri: images[2]}}/>

            </ImageCacheProvider>
        );
    }
}

API

This package exposes 3 modules:

const {
    CachedImage,            // react-native component that is a drop-in replacement for your react-native `Image` components
    ImageCacheProvider,     // a top level component that provides accsess to the underlying `ImageCacheManager` and preloads images
    ImageCacheManager,      // the logic behind cache machanism - ttl, fs, url resolving etc.
} = require('react-native-cached-image');

ImageCacheManager

This is where all the cache magic takes place. The API usually takes a URL and a set of ImageCacheManagerOptions.

ImageCacheManager.downloadAndCacheUrl(url: String, options: ImageCacheManagerOptions): Promise<String>

Check the cache for the the URL (after removing fixing the query string according to ImageCacheManagerOptions.useQueryParamsInCacheKey). If the URL exists in cache and is not expired, resolve with the local cached file path. Otherwise, download the file to the cache folder, add it to the cache and then return the cached file path.

ImageCacheManager.seedAndCacheUrl(url: String, seedPath: String, options: ImageCacheManagerOptions): Promise<String>

Check the cache for the the URL (after removing fixing the query string according to ImageCacheManagerOptions.useQueryParamsInCacheKey). If the URL exists in cache and is not expired, resolve with the local cached file path. Otherwise, copy the seed file into the cache folder, add it to the cache and then return the cached file path.

ImageCacheManager.deleteUrl(url: String, options: ImageCacheManagerOptions): Promise

Removes the cache entry for the URL and the local file corresponding to it, if it exists.

ImageCacheManager.clearCache(options: ImageCacheManagerOptions): Promise

Clear the URL cache and remove files in the cache folder (as stated in the ImageCacheManagerOptions.cacheLocation)

ImageCacheManager.getCacheInfo(options: ImageCacheManagerOptions): Promise.<{file: Array, size: Number}>

Returns info about the cache, list of files and the total size of the cache.

CachedImage

CachedImage is a drop in replacement for the Image component that will attempt to cache remote URLs for better performance.
It's main use is to hide the cache layer from the user and provide a simple way to cache images.
CachedImage uses an instance of ImageCacheManager to interact with the cache, if there is an instance provided by ImageCacheProvider via the context it will be used, otherwise a new instance will be created with the options from the component's props.

<CachedImage
    source={{
        uri: 'https://example.com/path/to/your/image.jpg'
    }}
    style={styles.image}
/>
Props
  • renderImage - a function that returns a component, used to override the underlying Image component.
  • activityIndicatorProps - props for the ActivityIndicator that is shown while the image is downloaded.
  • defaultSource - prop to display a background image while the source image is downloaded. This will work even in android, but will not display background image if there you set borderRadius on this component style prop
  • loadingIndicator - component prop to set custom ActivityIndicator.
  • fallbackSource - prop to set placeholder image. when source.uri is null or cached failed, the fallbackSource will be display.
  • any of the ImageCacheManagerOptionsPropTypes props - customize the ImageCacheManager for this specific CachedImage instance.

ImageCacheProvider

This is a top-level component with 2 major functions:

  1. Provide the customized ImageCacheManager to nested CachedImage.
  2. Preload a set of URLs.
Props
  • urlsToPreload - an array of URLs to preload when the component mounts. default []
  • numberOfConcurrentPreloads - control the number of concurrent downloads, usually used when the urlsToPreload array is very big. default urlsToPreload.length
  • onPreloadComplete - callback for when the preload is complete and all images are cached.

ImageCacheManagerOptions

A set of options that are provided to the ImageCacheManager and provide ways to customize it to your needs.

type ImageCacheManagerOptions = {
    headers: PropTypes.object,                      // an object to be used as the headers when sending the request for the url. default {}

    ttl: PropTypes.number,                          // the number of seconds each url will stay in the cache. default 2 weeks

    useQueryParamsInCacheKey: PropTypes.oneOfType([ // when handling a URL with query params, this indicates how it should be treated:
        PropTypes.bool,                             // if a bool value is given the whole query string will be used / ignored
        PropTypes.arrayOf(PropTypes.string)         // if an array of strings is given, only these keys will be taken from the query string.
    ]),                                             // default false

    cacheLocation: PropTypes.string,                // the path to the root of the cache folder. default the device cache dir

    allowSelfSignedSSL: PropTypes.bool,             // true to allow self signed SSL URLs to be downloaded. default false
};

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文