React-Native開發總結-webview
最近更新時間:2017年12月14日19:36:11
上學的時候希望儘早工作,融入社會,積累工作經驗。工作之後才發現,工作永遠幹不完,而且每個專案都不一樣,積累工作經驗不是一時半會的事情,而是日積月累細心領悟的過程,因此,需要不斷總結和積累所見所聞,保持學習,才能輕鬆駕馭工作。
在react native專案中,一方面使用RN技術進行APP開發,同時還能在APP中巢狀使用網頁,是常見的業務需求。常見方案有三種:使用html檔案、URI地址、html程式碼片段。
0、概述
import { WebView } from 'react-native';
WebView元件,用於建立一個原生的WebView,可以用於訪問一個網頁;
1、HTML程式碼片段在WebView中的使用
html程式碼片段如下,html程式碼片段的內容可以是圖文混編,來源於ajax介面返回的資料(string型別):
let HTML = '';
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
<style>
html {
font-size: 20px;
}
@media only screen and (min-width: 400px) {
html {
font-size: 21.33333333px !important;
}
}
@media only screen and (min-width: 414px) {
html {
font-size: 22.08px !important;
}
}
@media only screen and (min-width: 480px) {
html {
font-size: 25.6px !important;
}
}
body {
margin: 0;
padding: 1.5rem .8rem 1.5rem .8rem;
color: #424242;
line-height: 26px;
font-size: .8rem;
}
.content{
font-size: .8rem;
line-height: 1.3rem;
}
img {
width: 100%;
display: block;
margin: .5rem 0;
}
p{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div class="content">
<p>asdfasdf</p>
</div>
</body>
</html>
對HTML程式碼片段style樣式適配(如:禁止長按觸發)重置如下:
let arr = HTML.split("<style>");
let disableSelect =`* {-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;}`
if(arr.length > 1){
arr[1] = disableSelect + arr[1];
HTML = arr.join("<style>");
}
APP頁面使用方法:
<WebView
ref={webview => {this.webview = webview;}}
onError = {()=>{
ToastAndroid.show(`載入失敗,請重試!`,ToastAndroid.SHORT,ToastAndroid.CENTER);
this.props.navigation.goBack()
}}
javaScriptEnabled={true}
domStorageEnabled={true}
onMessage={this.onMessage}
source={{html: HTML}}
/>
獲取WebView元件例項的方法:
<WebView ref={webview => {this.webview01 = webview;}} />
console.log(this.webview01);//物件內容如下
<WebView ref={‘WEBVIEW01_REF’} />
console.log(this.refs[WEBVIEW01_REF]);//物件內容如下
2、uri地址在WebView中的使用
uri地址如下,uri的內容可以是PDF檔案、doc檔案,來源於ajax介面返回的資料(string型別):
let uri = 'http://abc.com/aa/bb/cc=='
<WebView
source={{uri: uri}}
/>
3、WebView元件例項詳解
WebView元件例項是一個WebView物件,包括屬性和方法,如下:
屬性:context、props(domStorageEnabled、javaScriptEnabled、onError()、onMessage()、saveFormDataDisabled、scalesPageToFit、source:{}、thirdPartyCookiesEnabled、ref)、refs、state
方法:goBack()、goForward()、onLoadingError()、reloadd()、postMessage()......
使用:
this.refs[WEBVIEW01_REF].onMessage();//在webview內部的網頁中呼叫window.postMessage方法時可以觸發此屬性對應的函式,從而實現網頁和RN之間的資料交換。 設定此屬性的同時會在webview中注入一個postMessage的全域性函式並覆蓋可能已經存在的同名實現。
未完,待續...