- 首页 > it技术 > >
React|React Native NetInfo判断网络状态
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 (
当前的网络状态:
{this.state.isConnected?'网络在线':'离线'}
当前的网络连接类型:
{this.state.connectionInfo}
当前连接的网络是否需要计费:
{NetInfo.isConnectionExpensive===true?'需要':'不需要'}
);
}}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 30
},
welcome: {
fontSize: 16,
textAlign: 'left',
margin: 10
}
});
推荐阅读