一、WebView组件介绍
使用 WebView 组件我们可以通过 url 来加载显示一个网页,也可以传入一段 html 代码来显示。下面对其主要属性和方法进行介绍。
1. 主要属性
source:在WebView中载入一段静态的html代码或是一个url(还可以附带一些header选项);automaticallyAdjustContentInsets:设置是否自动调整内容。格式:bool;contentInset:设置内容所占的尺寸大小。格式:{top:number,left:number,bottom:number,right:number};injectJavaScript:当网页加载之前注入一段 js 代码。其值是字符串形式。startInLoadingState:是否开启页面加载的状态,其值为 true 或者 false。bounces(仅iOS):回弹特性。默认为true。如果设置为false,则内容拉到底部或者头部都不回弹。scalesPageToFit(仅iOS):用于设置网页是否缩放自适应到整个屏幕视图,以及用户是否可以改变缩放页面。scrollEnabled(仅iOS):用于设置是否开启页面滚动。domStorageEnabled(仅Android):用于控制是否开启DOM Storage(存储)。javaScriptEnabled(仅Android):是否开启JavaScript,在 iOS 中的WebView是默认开启的。
2. 主要方法
onNavigationStateChange:当导航状态发生变化的时候调用。onLoadStart:当网页开始加载的时候调用。onError:当网页加载失败的时候调用。onLoad:当网页加载结束的时候调用。onLoadEnd:当网页加载结束调用,不管是成功还是失败。renderLoading:WebView组件正在渲染页面时触发的函数,只有startInLoadingState为 -true时该函数才起作用。renderError:监听渲染页面出错的函数。onShouldStartLoadWithRequest(仅iOS):该方法允许拦截WebView加载的 URL 地址,进行自定义处理。该方法通过返回true或者false来决定是否继续加载该拦截到请求。
二、WebView组件的使用样例
1. 通过url地址加载网页
(1)效果图
程序启动后,我们使用 WebView 加载 shq5785.blog.csdn.net 并全屏显示。
(2)样例代码
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Dimensions,
Text,
View,
WebView
} from 'react-native';
//获取设备的宽度和高度
var {
height: deviceHeight,
width: deviceWidth
} = Dimensions.get('window');
//默认应用的容器组件
class App extends Component {
//渲染
render() {
return (
<View style={styles.container}>
<WebView bounces={false}
scalesPageToFit={true}
source={{uri:"https://shq5785.blog.csdn.net/",method: 'GET'}}
style={{width:deviceWidth, height:deviceHeight}}>
</WebView>
</View>
);
}
}
//样式定义
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop:20
}
});
AppRegistry.registerComponent('HelloWorld', () => App);
2. 加载html代码
(1)效果图
我们传入一段 HTML 代码片段并显示。
(2)样例代码
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Dimensions,
Text,
View,
WebView
} from 'react-native';
//获取设备的宽度和高度
var {
height: deviceHeight,
width: deviceWidth
} = Dimensions.get('window');
//默认应用的容器组件
class App extends Component {
//渲染
render() {
return (
<View style={styles.container}>
<WebView bounces={false}
scalesPageToFit={true}
source={{html:"<h1 style='color:#ff0000'>欢迎访问 https://shq5785.blog.csdn.net/</h1>"}}
style={{width:deviceWidth, height:deviceHeight}}>
</WebView>
</View>
);
}
}
//样式定义
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop:20
}
});
AppRegistry.registerComponent('HelloWorld', () => App);
