首页 > 解决方案 > 没有互联网时 React Native webview

问题描述

我想在 webview 没有互联网时显示一条没有互联网的消息。我搜索了有关它的东西并没有找到它。有人能帮我吗 ?抱歉,我是 react-native 的新手。

编辑 1

import React, { Component } from 'react'
import { StyleSheet, Text, View, NetInfo } from 'react-native';
import WebViewComp from './web_view_comp.js'

export default class App extends Component {
   constructor(){
      super();
      this.state={
        connection_Status : ""
      }
    }
    componentDidMount() {
      NetInfo.isConnected.addEventListener(
          'connectionChange',
          this._handleConnectivityChange
      );
      NetInfo.isConnected.fetch().done((isConnected) => {
        if(isConnected == true){
          this.setState({connection_Status : "Online"})
        }
        else{
          this.setState({connection_Status : "Offline"})
        }
      });
    }


componentWillUnmount() {
  NetInfo.isConnected.removeEventListener(
      'connectionChange',
      this._handleConnectivityChange
  );
}

_handleConnectivityChange = (isConnected) => {
  if(isConnected == true){
      this.setState({connection_Status : "Online"})
    }
    else{
      this.setState({connection_Status : "Offline"})
    }
};


render() {
      if (this.state.connection_Status == "Online") {
         return (
            <WebViewComp/>
         )
      } else {
         return (
            <View style={styles.MainContainer}>
               <Text style={{fontSize: 20, textAlign: 'center', marginBottom: 20}}> Você está { this.state.connection_Status }</Text>
            </View>
         )
      }
   }
}
const styles = StyleSheet.create({
   MainContainer: {
     flex: 1,
     justifyContent: 'center',
     alignItems: 'center',
     backgroundColor: '#F5FCFF',
     padding: 20
   },

   TextStyle: {
     fontSize:20,
     textAlign: 'center',
   }

 });

`

我根据帮助编辑了代码,我得出了这个结果,但是我相信如果这个人连接了移动互联网并且没有移动数据可能会出现问题。

标签: react-nativereact-native-androidreact-native-ios

解决方案


您可以使用这样onError的事件WebView

//declarations and imports
state={isError:false}
render(){
   return(
       <WebView onError={()=>alert("Something went wrong")} />
       )}

如果您想知道是否有互联网,请跟踪onError.


推荐阅读