zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

《React-Native系列》29、 RN组件之WebView

webview组件React 系列 native 29 Rn
2023-09-27 14:29:03 时间

说起WebView,我们还是很熟悉的吧。

特别是做过Hybrid开发的同学,Web+Native一个很经典的开发模式,包括现在依然很多App上都在使用。


我们列举几个比较重要的属性吧

source {uri: string, method: string, headers: object, body: string}, {html: string, baseUrl: string}, number 
在WebView中载入一段静态的html代码或是一个url(还可以附带一些header选项)。

onError function  方法 当网页加载失败的时候调用
onLoad  function 方法  当网页加载结束的时候调用
onLoadEnd fucntion 当网页加载结束调用,不管是成功还是失败
onLoadStart  function  当网页开始加载的时候调用
onNavigationStateChange function方法  当导航状态发生变化的时候调用
renderError  function  该方法用于渲染一个View视图用来显示错误信息
renderLoagin function  该方法用于渲染一个View视图用来显示一个加载进度指示器
startInLoadingState  bool
domStorageEnabled bool  该适合Android平台 该只适合于Android平台,用于控制是否开启DOM Storage(存储)
javaScriptEnabled  bool  该适合于Android平台,是否开启JavaScript,在iOS中的WebView是默认开启的
onShouldStartLoadWithRequest  function  

该适合iOS平台,该允许拦截WebView加载的URL地址,进行自定义处理。该方法通过返回true或者falase来决定是否继续加载该拦截到请求

scalesPageToFit  bool  该适合iOS平台  用于设置网页是否缩放自适应到整个屏幕视图以及用户是否可以改变缩放页面
scrollEnabled  bool    该适合iOS平台 用于设置是否开启页面滚动 ,默认为ture


好,那我们开始撸代码吧。

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. 'use strict';  
  2. import React, { Component } from 'react';  
  3. import {  
  4.   StyleSheet,  
  5.   View,  
  6.   WebView,  
  7.   Dimensions,  
  8. } from 'react-native';  
  9.   
  10. const {width, height} = Dimensions.get('window');  
  11.   
  12. const url = "http://www.58.com";  
  13. export default class WebViewExample extends Component {  
  14.   
  15.   constructor(props) {  
  16.     super(props);  
  17.   }  
  18.   
  19.   render() {  
  20.     return (  
  21.       <View style={styles.container}>  
  22.         <WebView  
  23.           style={{width:width,height:height-20,backgroundColor:'gray'}}  
  24.           source={{uri:url,method: 'GET'}}  
  25.           javaScriptEnabled={true}  
  26.           domStorageEnabled={true}  
  27.           scalesPageToFit={false}  
  28.           />  
  29.       </View>  
  30.     );  
  31.   }  
  32. }  
  33.   
  34. const styles = StyleSheet.create({  
  35.   container: {  
  36.     flex: 1,  
  37.     backgroundColor: '#f2f2f2',  
  38.     paddingTop:20,  
  39.   },  
  40. });  

整个代码非常简单。

只是加载了一个58的网页,Webview铺满整个手机屏幕。


在调试的过程中,发现报异常如下:


不要怕,解决方案如下:

在Info.plist中添加NSAppTransportSecurity类型Dictionary。在NSAppTransportSecurity下添加Allow Arbitrary Loads类型Boolean,值设为YES



运行效果如下: