一. 簡介
在原生開發(fā)中加載網(wǎng)頁時經(jīng)常用到WebView ,RN也給我們提供了WebView控件,可以用于訪問一個網(wǎng)頁。
二. 屬性
- automaticallyAdjustContentInsets
是否自動調(diào)整內(nèi)部內(nèi)容 - allowsInlineMediaPlayback bool (ios)
指定HTML5視頻是在網(wǎng)頁當前位置播放還是使用原生的全屏播放器播放。 默認值為false。
注意 : 要讓視頻在網(wǎng)頁中播放,不光要將這個屬性設為true,HTML中的視頻元素本身也需要包含webkit-playsinline屬性。 - bounces bool (ios)
- contentInset {top: number, left: number, bottom: number, right: number}
內(nèi)部內(nèi)容偏移值 該值為一個JavaScript對象 - dataDetectorTypes enum('phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all'), [object Object]
探測網(wǎng)頁中某些特殊數(shù)據(jù)類型,自動生成可點擊的鏈接,默認情況下僅允許探測電話號碼。
你可以指定探測下述類型中的一種,或者使用數(shù)組來指定多個類型。
dataDetectorTypes的可選值:
'phoneNumber'
'link'
'address'
'calendarEvent'
'none'
'all' - domStorageEnabled bool (android)
指定是否開啟DOM本地存儲。 - injectedJavaScript string
注入的js代碼,其值為字符串,如果加上了該屬性,就會在webview里面執(zhí)行js代碼(在網(wǎng)頁加載之前注入) - mediaPlaybackRequiresUserAction bool
設置頁面中的HTML5音視頻是否需要在用戶點擊后再開始播放。默認值為true. - source:{{uri:'網(wǎng)址'}}
在WebView中載入一段靜態(tài)的html代碼或是一個url(還可以附帶一些header選項){{html:'html代碼塊'}} - onError function
加載失敗時調(diào)用。 - onLoad function
加載成功時調(diào)用。 - onLoadEnd function
加載結(jié)束時(無論成功或失?。┱{(diào)用。 - onLoadStart function
加載開始時調(diào)用。 - onMessage function
在webview內(nèi)部的網(wǎng)頁中調(diào)用window.postMessage方法時可以觸發(fā)此屬性對應的函數(shù),從而實現(xiàn)網(wǎng)頁和RN之間的數(shù)據(jù)交換。 設置此屬性的同時會在webview中注入一個postMessage的全局函數(shù)并覆蓋可能已經(jīng)存在的同名實現(xiàn)。
網(wǎng)頁端的window.postMessage只發(fā)送一個參數(shù)data,此參數(shù)封裝在RN端的event對象中,即event.nativeEvent.data。data 只能是一個字符串。 - javaScriptEnabled bool (android)
iOS平臺JavaScript是默認開啟的。 - onNavigationStateChange function
監(jiān)聽導航狀態(tài)變化的函數(shù)(當發(fā)現(xiàn)瀏覽器地址改變時,觸發(fā)事件) - onShouldStartLoadWithRequest function (ios)
允許為webview發(fā)起的請求運行一個自定義的處理函數(shù)。返回true或false表示是否要繼續(xù)執(zhí)行響應的請求。 - renderError function
設置一個函數(shù),返回一個視圖用于顯示錯誤。 - startInLoadingState
是否開啟頁面加載的狀態(tài) - renderLoading function
webview組件正在渲染頁面時觸發(fā)的函數(shù),需要同startInLoadingState一起使用,當startInLoadingState為true時該函數(shù)才起作用 - scalesPageToFit bool
設置是否要把網(wǎng)頁縮放到適應視圖的大小,以及是否允許用戶改變縮放比例。 - scrollEnabled bool (ios)
表示webview里面頁面是否能滾動,如果其值為true則可以滾動,否則禁止?jié)L動 - userAgent string (android)
為WebView設置user-agent字符串標識。這一字符串也可以在原生端用WebViewConfig來設置,但js端的設置會覆蓋原生端的設置。
三. 示例
const screenWidth =Dimensions.get('window').width; const screenHeight =Dimensions.get('window').height;
render(){ return (
<View style={styles.flex}> <WebView style={{width:screenWidth , height:screenHeight }} source={{uri:'http://www.baidu.com'}} {/*injectedJavaScript ={"alert('測試一下injectedJavaScript屬性')"}*/}> </WebView> </View>
); }
效果

webview_01.png