1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| import React, { useState, useEffect } from 'react'; import { View, Text, Switch, FlatList, TouchableOpacity, StyleSheet } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context';
const API_URL = 'http://your-server:3000/api';
export default function App() { const [devices, setDevices] = useState([]); const [sensors, setSensors] = useState({ temp: 0, humid: 0 });
useEffect(() => { fetchDevices(); const interval = setInterval(fetchSensors, 5000); return () => clearInterval(interval); }, []);
const fetchDevices = async () => { const res = await fetch(`${API_URL}/devices`); const data = await res.json(); setDevices(data); };
const fetchSensors = async () => { const res = await fetch(`${API_URL}/sensors`); const data = await res.json(); setSensors(data); };
const toggleDevice = async (deviceId, currentState) => { await fetch(`${API_URL}/control`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ device: deviceId, state: !currentState }) }); fetchDevices(); };
const renderDevice = ({ item }) => ( <View style={styles.deviceItem}> <Text style={styles.deviceName}>设备 {item[0]}</Text> <Switch value={item[1]} onValueChange={() => toggleDevice(item[0], item[1])} /> </View> );
return ( <SafeAreaView style={styles.container}> <View style={styles.header}> <Text style={styles.title}>智能家居</Text> <View style={styles.sensorCard}> <Text>温度: {sensors.temp}°C</Text> <Text>湿度: {sensors.humid}%</Text> </View> </View> <FlatList data={devices} renderItem={renderDevice} keyExtractor={item => item[0]} /> </SafeAreaView> ); }
const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f5f5f5' }, header: { padding: 20 }, title: { fontSize: 24, fontWeight: 'bold' }, sensorCard: { flexDirection: 'row', justifyContent: 'space-around', marginTop: 10, padding: 15, backgroundColor: '#fff', borderRadius: 10 }, deviceItem: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 20, backgroundColor: '#fff', marginTop: 10, marginHorizontal: 20, borderRadius: 10 } });
|