在這次使用過程中,分別去嘗試了三個組件,來解析HTML代碼和URL:
- 原生的
WebView
- 第三方組件
react-native-htmlview
- 官方推薦的替代原生
WebView
的react-native-webview
一、組件對比
1. 原生的WebView
優點:
- 同時可以解析HTML代碼和URL鏈接。
缺點:
- 內容顯示不完全,最右側文字。
- 高度無法自適應。
由於無法做到高度自適應,,所以放棄研究原生的WebView
,看到網上有推薦第三方組件react-native-htmlview
。從而轉戰研究react-native-htmlview
。
2. react-native-htmlview中的WebView組件
優點:
- 高度自適應。
缺點:
- 該組件只能解析HTML代碼,無法解析URL鏈接。
不滿足需求,放棄,回到官方文檔中,有推薦 react-native-webview
,從而轉戰react-native-webview
中的WebView
組件。
3. react-native-webview中的WebView組件
優點:
- 內容顯示完全。
- 同時可以解析HTML代碼和URL鏈接。
- 完全複用原生的
WebView
的所有屬性。
缺點:
- 高度無法自適應。
二、使用
原生的WebView
和 react-native-webview
在解析HTML代碼的時候,需要做HTML代碼結構處理,否則直接解析的話,無法使用自動設置高度。後端返回的代碼時通過<br>
來分段的。
html
代碼段處理:
const html = `<!DOCTYPE html>
<html>
<body>
${html_code}
<script>
window.onload=function(){
window.location.hash = 1;
document.title = document.body.clientHeight;
}
</script>
</body>
</html>`;
通過這個,從而可以在WebView
的onNavigationStateChange
的函數中獲取到內容實際高度。
使用:
<View style={{height:this.state.height}}>
<WebView
source={{ html: html}}
scalesPageToFit={false}
automaticallyAdjustContentInsets={false}
scrollEnabled={false}
onNavigationStateChange={(navState)=>{
if(!isNaN(parseInt(navState.title))) {
this.setState({
height:parseInt(navState.title) + 20
})
}
}}
/>
</View>
- 此處的
WebView
是指的是 原生的WebView
和react-native-webview
中的WebView
組件。react-native-webview
中的WebView
組件 從源代碼上來說其實也是封裝的原生的WebView
。- 兩個組件的參考文檔:https://reactnative.cn/docs/webview/
三、其他
樣式問題:
可以使用內聯樣式,參考css 來設置就可以。無法識別通過StyleSheet.create()
創建的樣式。
圖片問題
圖片的src
可以是url
,也可以是轉換之後的data:base64
,無法使用本地圖片。
四、待解決問題
當 WebView
的 source
爲url
的時候,暫無法做到高度自適應。
tips:當解析HTML代碼出現亂碼的時候,在
source
屬性設置上加上source={{html: html,baseUrl:''}}
。完美解決問題。