需要使用 react-native-fetch-blob 下载本地图像
Require local image downloaded with react-native-fetch-blob
我试图在我的图像组件中要求使用 react-native-fetch-blob 下载图像,但是当我给它图像路径时它一直说我«未知命名模块:'/Users/…/图书馆/…'
要求图像存储在本地目录中的正确方法是什么?
let imagePath = null
RNFetchBlob
.config({
fileCache : true
})
.fetch('GET', uri)
// the image is now dowloaded to device's storage
.then((resp) => {
// the image path you can use it directly with Image component
imagePath = resp.path()
this.setState({ uri: require(imagePath) })
try {
AsyncStorage.setItem(`${this.props.uri}`, imagePath);
} catch (error) {
console.log(error)
}
})
我的渲染方法:
render() {
return(
<Image style={this.props.style} source={this.state.uri} />
)
}
问题不是因为我将变量设置为源,因为当我在下载后输入类似 this.setState({ uri: require('../images/test.jpg') })
的内容时它正在工作。
require(imagePath)
的存在是为了帮助打包器找到本地图像并将它们放置到应用程序包中。
当您需要显示动态加载的图像时,您只需将 file
位置作为 URI 传递,例如:
render() {
const imageAbsolutePath = this.state.imagePath;
const imageUri = 'file://' + imageAbsolutePath;
return <Image source={{uri: imageUri}}/>;
}
因此,在这种情况下您不需要任何 require
语句。
我试图在我的图像组件中要求使用 react-native-fetch-blob 下载图像,但是当我给它图像路径时它一直说我«未知命名模块:'/Users/…/图书馆/…'
要求图像存储在本地目录中的正确方法是什么?
let imagePath = null
RNFetchBlob
.config({
fileCache : true
})
.fetch('GET', uri)
// the image is now dowloaded to device's storage
.then((resp) => {
// the image path you can use it directly with Image component
imagePath = resp.path()
this.setState({ uri: require(imagePath) })
try {
AsyncStorage.setItem(`${this.props.uri}`, imagePath);
} catch (error) {
console.log(error)
}
})
我的渲染方法:
render() {
return(
<Image style={this.props.style} source={this.state.uri} />
)
}
问题不是因为我将变量设置为源,因为当我在下载后输入类似 this.setState({ uri: require('../images/test.jpg') })
的内容时它正在工作。
require(imagePath)
的存在是为了帮助打包器找到本地图像并将它们放置到应用程序包中。
当您需要显示动态加载的图像时,您只需将 file
位置作为 URI 传递,例如:
render() {
const imageAbsolutePath = this.state.imagePath;
const imageUri = 'file://' + imageAbsolutePath;
return <Image source={{uri: imageUri}}/>;
}
因此,在这种情况下您不需要任何 require
语句。