import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import WiFiP2p from 'react-native-wifi-p2p';
export default function App() {
const [wifiP2pState, setWifiP2pState] = useState('未初始化');
useEffect(() => {
WiFiP2p.initialize(
() => setWifiP2pState('初始化成功'),
(error) => setWifiP2pState(`初始化失败: ${error}`),
WiFiP2p.CONNECTION_INFO_AVAILABLE,
);
}, []);
return (
<View style={styles.container}>
<Text style={styles.text}>Wi-Fi P2P 状态: {wifiP2pState}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 20,
textAlign: 'center',
},
});
这段代码展示了如何在React Native应用中初始化Wi-Fi Direct (P2P)库,并在应用的UI中显示初始化结果。代码使用了React Hooks (useEffect
和useState
)来管理副作用和组件状态,这是React Native的当前推荐做法。