This is documentation for the next SDK version. For up-to-date documentation, see the latest version (SDK 55).
@react-native-community/netinfo
一个跨平台 API,可用于访问网络信息。
Android
iOS
tvOS
Web
Included in Expo Go
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
@react-native-community/netinfo 允许你获取有关连接类型和连接质量的信息。
安装
Terminal
- npx expo install @react-native-community/netinfoIf 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
要导入此库,请使用:
import NetInfo from '@react-native-community/netinfo';
如果你只想获取一次网络连接信息,可以使用:
NetInfo.fetch().then(state => { console.log('连接类型', state.type); console.log('是否已连接?', state.isConnected); });
或者,如果你更希望订阅网络状态更新(这样就可以在网络状态变化时运行代码/执行操作),请使用:
const unsubscribe = NetInfo.addEventListener(state => { console.log('连接类型', state.type); console.log('是否已连接?', state.isConnected); }); // 要取消订阅这些更新,只需使用: unsubscribe();
获取 SSID
要访问 ssid 属性(可在 state.details.ssid 下获取),还需要一些额外的配置步骤:
- 使用
Location.requestForegroundPermissionsAsync()或Location.requestBackgroundPermissionsAsync()请求位置权限。
仅限 iOS
-
在 app.json 的
ios.entitlements下添加com.apple.developer.networking.wifi-info权限:app.json"ios": { "entitlements": { "com.apple.developer.networking.wifi-info": true } } -
在你应用的 App Identifier 中勾选 Access Wi-Fi Information 选项,可在此处找到。
-
使用
eas build --platform ios或npx expo run:ios重新构建你的应用。
了解更多
访问官方文档
获取有关 API 及其使用方式的完整信息。