@react-native-community/netinfo

提供对网络信息的访问的跨平台 API。

Android
iOS
tvOS
Web
Bundled version:
11.4.1

@react-native-community/netinfo 允许你获取有关连接类型和连接质量的信息。

¥@react-native-community/netinfo allows you to get information about connection type and connection quality.

安装

¥Installation

Terminal
npx expo install @react-native-community/netinfo

If you are installing this in an existing React Native app, make sure to install expo in your project. Then, follow the installation instructions provided in the library's README or documentation.

API

要导入该库,请使用:

¥To import this library, use:

import NetInfo from '@react-native-community/netinfo';

如果你只想获取有关网络连接的信息一次,你可以使用:

¥If you want to grab information about the network connection just once, you can use:

NetInfo.fetch().then(state => {
  console.log('Connection type', state.type);
  console.log('Is connected?', state.isConnected);
});

或者,如果你想订阅有关网络状态的更新(这样你就可以在网络状态发生变化时运行代码/执行操作),请使用:

¥Or, if you'd rather subscribe to updates about the network state (which then allows you to run code/perform actions anytime the network state changes) use:

const unsubscribe = NetInfo.addEventListener(state => {
  console.log('Connection type', state.type);
  console.log('Is connected?', state.isConnected);
});

// To unsubscribe to these update, just use:
unsubscribe();

访问 SSID

¥Accessing the SSID

要访问 ssid 属性(在 state.details.ssid 下可用),需要执行一些额外的配置步骤:

¥To access the ssid property (available under state.details.ssid), there are a few additional configuration steps:

仅限 iOS

¥iOS only

  • com.apple.developer.networking.wifi-info 权利添加到 ios.entitlements 下的 app.json 中:

    ¥Add the com.apple.developer.networking.wifi-info entitlement to your app.json under ios.entitlements:

app.json
    "ios": {
      "entitlements": {
        "com.apple.developer.networking.wifi-info": true
      }
    }

了解更多

¥Learn more

访问官方文档

获取有关 API 及其用法的完整信息。