【问题标题】:Show local image inside html in webview when the device is offline in react-native当设备在 react-native 中离线时,在 webview 中显示本地图像
【发布时间】:2021-02-10 15:19:38
【问题描述】:
我的文章由页面上的不同图像组成,这些图像也本地存储在我的设备上。当设备失去连接时,相同的文章在 webview 中显示为本地存储的 html,但是图像没有加载(这是有道理的),问题是 - 如何修改 html,以便当设备离线而不是尝试从链接中获取图像,以指向本地图像。非常感谢任何帮助。
谢谢
【问题讨论】:
标签:
android
html
ios
react-native
webview
【解决方案1】:
react-native-webview 允许您注入 javascript,所以我所做的只是编辑您的 html 并为您的图像提供一个名为 myImage 的 id。我创建了一个名为 isOnline 的功能状态,当设置为 false 时,它将 javascript 函数传递到 webview 并显示您想要的离线图像。要获取您设备的网络连接状态,请参阅react-native-community/netinfohttps://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>`