我有一个 react native 应用程序,它从外部来源下载图像并将它们保存到专用的本地缓存文件夹中。稍后它们会显示在不同的 View 中。这些图像最初在应用程序包中不可用。
<Image source={{uri: uri}} resizeMode="contain" style={style} />
我将 URI 格式用于引用本地文件夹的图像组件的源输入参数。我也将宽度和高度作为样式传递,实际上图像大小在绘制之前总是已知的。它在 iOS 上运行良好,但在 Android 上运行不佳。
如文档所述,我应该对 Android 上的本地镜像使用 require('')。这适用于静态图像,但不适用于运行时下载。
有人知道我该如何解决这个问题吗?
代码如下:
class CachedImage extends React.Component {
state = {
uri: null
}
async _handleCache(source) {
const path = `${RNFetchBlob.fs.dirs.CacheDir}${sha1(source.uri).toString()}.jpg`;
const exists = await RNFetchBlob.fs.exists(path);
if (exists) {
this.setState({uri: path});
} else {
// encoding the file to preserve proper URL transmition
await RNFetchBlob
.config({path})
.fetch("GET", source.uri, {});
this.setState({uri: path});
}
}
componentWillMount() {
this._handleCache(this.props.source).done();
}
render() {
const { style } = this.props;
if (this.state.uri != null) {
return (
<Image source={{uri: this.state.uri}} resizeMode="contain" style={style} />
);
}
return(
<View style={style}/> //todo: display activity while loading ...
);
}
}
用法:
<CachedImage
style={{width: _width , height: _height}}
source={{uri: 'http://...'}} />
最佳答案
导入这个包
import { StyleSheet, Image, Dimensions } from 'react-native';
像这样渲染图像
<Image source={{uri: uri}} style={styles.image} />
在底部添加这个样式
const styles = StyleSheet.create({
image: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').width / 2
}
});
如果有任何问题,请将其写在下面,这应该有效!
关于android - 未显示使用 uri 作为源的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50347387/