android - 当设备在 react-native 中离线时,在 webview 中显示本地图像
问题描述
我有一篇由页面上不同图像组成的文章,这些图像也本地存储在我的设备上。当设备失去连接时,相同的文章在 webview 中显示为本地存储的 html,但是图像没有加载(这是有道理的),问题是 - 如何修改 html,以便当设备离线而不是尝试从链接中获取图像,以指向本地图像。任何帮助是极大的赞赏。
谢谢
解决方案
react-native-webview
允许您注入 javascript,所以我所做的只是编辑您的 html 并为您的图像提供一个名为myImage
. 我创建了一个名为 的功能状态isOnline
,当设置为 false 时,将 javascript 函数传递到 webview 并显示您想要的离线图像。react-native-community/netinfo
要获取设备的网络连接状态, 请参阅https://github.com/react-native-netinfo/react-native-netinfo。为了更好地阅读,样式已从您的 html 中删除,因此请根据需要将其重新包含在内。
export const MyWebViewComponent = () => {
const WebViewRef
const [isOnline, setIsOnline] = useState(false)
const [placeholderImgSrc, setPlaceholderImgSrc] = useState(
'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/dog-puppy-on-garden-royalty-free-image-1586966191.jpg?crop=1.00xw:0.669xh;0,0.190xh&resize=1200:*'
)
useEffect(
() => {
if (!isOnline) {
WebViewRef.injectJavaScript(
`(function(){ document.getElementById('myImage').src='${placeholderImgSrc}' })(); true;`
) //or simply do WebViewRef.injectJavaScript(`document.getElementById('myImage').src='${ placeholderImgSrc }'; true;`)
}
},
[isOnline]
)
return (
<View>
<WebView ref={(ref) => (WebViewRef = ref)} style={{ flex: 1 }} originWhitelist={['*']} source={{ html: html }} />
</View>
)
}
const html = `<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8" />
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="contentdiv" class="article-content">
<p><strong>text</strong>text</p> <br />
<p><strong>text</strong> text</p> <br />
<aside class="storyBoxout">
<figure class="has-text">
<div class="preview item">
<img id = "myImage" alt="" sizes="(max-width: 440px) 320px"
src="https://testlink.com/shimg/zx320y230c_4130819.jpg"
srcset="https://testlink.com/shimg/zx320y230c_4130819.jpg 320w, https://testlink.com/shimg/zx640y460c_4130819.jpg 640w">
</div>
<figcaption>
</div>
<script>
</script>
</body>
</html>`
推荐阅读
- xamarin - Xamarin.Forms UWP 上的缩放动画不重复
- sql - AdventureWorks 2016 子查询不起作用
- php - 如何在 Laravel 的 LoginPage 上调试 419 错误?(不使用 AJAX)
- python - 在python中调用没有WSDL的soap API
- python - OpenCV 图片卡住了
- python - 是什么阻止用户被插入到表中?
- javascript - 有没有办法只在索引上显示 PWA“添加到主屏幕”?
- uwp-xaml - UWP 导航视图选择指示器
- javascript - 将表单数据和字符串列表发布到控制器
- javascript - 异步/等待读取 blob?