美文网首页React Native
React Native NetInfo判断网络状态

React Native NetInfo判断网络状态

作者: 想成为大牛的小白 | 来源:发表于2017-08-22 13:26 被阅读0次
    import React, { Component } from 'react';
    import {
        AppRegistry,
        StyleSheet,
        View,
        Text,
        NetInfo,
        Toast
    } from 'react-native';
    // import NetWorkTool from './src/Net/NetWorkTool';
    class Login extends Component {
        constructor(props){
            super(props);
            this.state={
                isConnected:null,
                connectionInfo:null
            }
        }
    
        componentDidMount() {
            //检测网络是否连接
            NetInfo.isConnected.fetch().done((isConnected)=>{
                this.setState({isConnected});
            });
        //    检测网络连接信息
            NetInfo.fetch().done((connectionInfo)=>{
                this.setState({connectionInfo});
            });
        //    检测网络变化事件
            NetInfo.addEventListener('change',(networkType)=>{
               this.setState({isConnected:networkType})
            })
        }
        render() {
            return (
                <View style={styles.container}>
                    <Text style={styles.welcome}>
                    当前的网络状态:
                    {this.state.isConnected?'网络在线':'离线'}
                </Text>
                <Text style={styles.welcome}>
                    当前的网络连接类型:
                    {this.state.connectionInfo}
                </Text>
                <Text style={styles.welcome}>
                    当前连接的网络是否需要计费:
                    {NetInfo.isConnectionExpensive===true?'需要':'不需要'}
                </Text>
                </View>
            );
        }
    
    }
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            paddingTop: 30
        },
        welcome: {
            fontSize: 16,
            textAlign: 'left',
            margin: 10
        }
    });
    

    相关文章

      网友评论

        本文标题:React Native NetInfo判断网络状态

        本文链接:https://www.haomeiwen.com/subject/njqldxtx.html