react-native NetInfo

来源:互联网 发布:steam汽车模拟软件 编辑:程序博客网 时间:2024/05/18 01:22
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */import React, { Component } from 'react';import {  AppRegistry,  StyleSheet,  Text,  View,  Linking,  NetInfo} from 'react-native';export default class D20170503 extends Component {    constructor(props){        super(props);        this.state = {            isCon:false,            conInfo:null,            isFree:false        }    }    componentDidMount() {        //监听网络是否链接        NetInfo.isConnected.addEventListener('isCon',this.isCon.bind(this));        //监听网络变化        NetInfo.addEventListener('changeCon',this.changeCon.bind(this));        //检查网络是否链接 返回true/fase        NetInfo.isConnected.fetch().done((b) => {            this.setState({                isCon:b            });        });        //网络链接的信息        NetInfo.fetch().done((info) => {            conInfo:info        });        // 用于判断当前活动的连接是否计费        NetInfo.isConnectionExpensive().then((state) =>{            this.setState({                isFree:state            });        });    }    isCon(b){        this.setState({            isCon:b        });    }    changeCon(info){        this.setState({            conInfo:info        });    }    componentWillUnmount() {        //移除监听        NetInfo.isConnected.removeEventListener('isCon',this.isCon);        NetInfo.removeEventListener('changeCon',this.changeCon);    }  render() {    return (      <View style={styles.container}>          <Text>{'是否联网: ' +this.state.isCon}</Text>          <Text>{'联网信息: ' +this.state.conInfo}</Text>          <Text>{'是否计费: ' +this.state.isFree}</Text>      </View>    );  }}const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: 'center',    alignItems: 'center',    backgroundColor: '#F5FCFF',  },});AppRegistry.registerComponent('D20170503', () => D20170503);

0 0
原创粉丝点击