一、介绍
WebView组件进行创建渲染一个原生的WebView,可以加载一个网页,并且具有网页的特性。
二、属性
style 继承可以使用View组件的所有属性和Style
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视图用来显示错误信息
startInLoadingState bool 控制加载指示器是否可以显示
renderLoading function 返回加载指示器
三、注意事项
1、给的网址链接必须加 http:// 否则访问不了
2、很多属性其实试验了,但是没有看出有什么效果,就没有写上来
3、react-native-webview-bridge和react-native-webtrc是两个可以和页面通信的插件
四、完整代码
效果图
代码
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
WebView,
TouchableHighlight,
Alert
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
src: 'http://www.oschina.net/'
};
}
goQQ=()=> {
this.setState({
src:'http://www.qq.com/'
});
}
goOSC=()=> {
this.setState({
src:'http://www.oschina.net/'
});
}
goBack=()=> {
this.refs.webview.goBack();
}
goForward=()=>{
this.refs.webview.goForward();
}
reload=()=> {
this.refs.webview.reload();
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<View style={[styles.left]}>
<TouchableHighlight
onPress={()=>this.goOSC()}
>
<Text style={[styles.text]}>OSChina</Text>
</TouchableHighlight>
</View>
<View style={[styles.left]}>
<TouchableHighlight
onPress={()=>this.goQQ()}
>
<Text style={[styles.text]}>腾讯图片</Text>
</TouchableHighlight>
</View>
</View>
<View style={styles.subHeader}>
<TouchableHighlight
onPress={()=>this.goBack()}
>
<Text style={[styles.text]}>后退</Text>
</TouchableHighlight>
<TouchableHighlight
onPress={()=>this.reload()}
>
<Text style={[styles.text]}>刷新</Text>
</TouchableHighlight>
<TouchableHighlight
onPress={()=>this.goForward()}
>
<Text style={[styles.text]}>前进</Text>
</TouchableHighlight>
</View>
<WebView
ref="webview"
source={{uri:this.state.src}}
startInLoadingState={true}
renderLoading={()=><Text>正在加载页面...</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
header:{
flexDirection:'row',
justifyContent:'space-between',
height:60,
backgroundColor:'green',
},
subHeader:{
flexDirection:'row',
justifyContent:'space-between',
height:60,
backgroundColor:'yellow',
},
text: {
color: '#333333',
marginBottom: 5,
backgroundColor:'#00ced1',
fontSize: 25,
textAlign:'center',
},
left:{
justifyContent:'center',
alignItems:'center'
},
right:{
justifyContent:'center',
alignItems:'center'
}
});
参考文章
https://github.com/facebook/react-native/tree/master/Examples/UIExplorer
http://reactnative.cn/docs/0.25/webview.html#content
免责说明
1、本博客中的文章摘自网上的众多博客,仅作为自己知识的补充和整理,并分享给其他需要的coder,不会用于商用。
2、因为很多博客的地址看完没有及时做保存,所以很多不会在这里标明出处,非常感谢各位大牛的分享,也希望大家理解。