react-native - React Native:将图像源声明为函数时出现问题?
问题描述
这是我试图用 React Native 做的事情:
- 从数据库中获取图像 URL 数据。
- 检查图像是否存在于存储中。
- 如果图像存在,则渲染它。如果不是,则渲染占位符图像。
基本上,我声明了一个函数来执行步骤 2 和 3,并将其作为 Image 组件中的源。但是,即使目标图像存在于带有 URL 的存储中,Image 组件也不会渲染任何图像。
这里可能发生了什么?这是我正在使用的代码。不明白为什么这段代码不起作用……也许是语法错误?什么可能是修复/更好的方法来做到这一点?
//The function to check if the image actually exists and return placeholder if not
const checkImageURL = (url) => {
const placeholder_url='url_of_placeholder_image';
fetch(url)
.then(res => {
if(res.status == 404){
return placeholder_url;
}
else{
return url;
}
})
.catch(err=>{return placeholder_url})
}
//The way I declared the source for the image
<Image source={uri:checkImageURL(url)} style={style.mainImage}/>
解决方案
远程 URL 的 source prop 必须是一个对象,所以你需要再添加一个花括号
<Image source={{uri:checkImageURL(url)}} style={style.mainImage}/>
有关道具中花括号的更多信息here
推荐阅读
- c# - NEST:从 ElasticSearch 中的搜索响应 (ISearchResponse) 获取数据的问题
- python - 安排不和谐命令
- sql - SQL 更新问题
- javascript - 单击外部时关闭模态窗口
- javascript - 输入单词是否按字母顺序排列?
- c++ - 如何使用类型级函数动态创建静态类型?
- node.js - Stripe 从会话对象中获取 product_id / price_id
- javascript - 如何仅从字符串中提取数字,但数字开头具有特殊字符的子字符串除外
- cmake - 命令 msbuild INSTALL.vcxproj 错误的 io2d 错误
- python - 如何使用 yolov4 的检测来绘制边界框?