代码
1 import React, {Component} from 'react';
2 import {Platform, View, WebView, BackHandler,Dimensions,StyleSheet,Text,ToastAndroid} from 'react-native';
3
4 var WEB_URL = "https://www.ly.com/FlightQuery.aspx";
5 var WEB_VIEW_REF = 'webview';
6 const {width, height} = Dimensions.get('window');
7 export default class App extends Component {
8 constructor(props) {
9 super(props);
10 this.state = {
11 webUrl: WEB_URL,
12 scalesPageToFit: false,
13 };
14 // 添加返回键监听
15 this.addBackHandlerListener(this.props.navigator);
16 }
17
18 render() {
19 return (
20 <View style={styles.container}>
21 <WebView
22 style={{width,height:height-20,backgroundColor:'white'}}
23 ref={WEB_VIEW_REF}
24 source={{uri: this.state.webUrl}}
25 javaScriptEnabled={true}//是否开启js
26 domStorageEnabled={true}//是否开启存储
27 scalesPageToFit={true}//用户是否可以改变页面
28 startInLoadingState={true}
29 onNavigationStateChange={this.onNavigationStateChange}
30 renderLoading={() => {
31 return <View style={styles.conText}><Text style={styles.txt}>正在加载Loading...</Text></View>
32 }}
33 />
34
35 </View>
36 );
37 }
38
39 // 监听返回键事件
40 addBackHandlerListener() {
41 if (Platform.OS === 'android') {
42 BackHandler.addEventListener('hardwareBackPress', this.onBackHandler);
43 }
44 }
45
46 onBackHandler = ()=> {//返回true代表不调用默认返回功能,返回false代表退出当前界面。
47
48 if (this.state.backButtonEnabled) {
49 this.refs[WEB_VIEW_REF].goBack();//回退<WebView>控件内部跳转的页面
50 return true;
51 } else {
52 return false;
53
54 }
55 };
56
57 onNavigationStateChange = (navState)=> {//WebView内部跳转后状态改变时回调:
58 this.setState({
59 backButtonEnabled: navState.canGoBack,//改变this.state.backButtonEnabled状态
60 });
61 };
62 }
63 const styles = StyleSheet.create({
64 container: {
65 flex: 1,
66 backgroundColor: '#f2f2f2',
67 //paddingTop:20,
68 },
69 conText:{
70 flex: 1,
71 alignItems: 'center',
72 justifyContent: 'center'
73 },
74 txt:{
75 fontSize:20,
76 }
77 });