鸿蒙原生开发手记徒步迹 - 天气卡片组件开发集成天气数据打造实用的首页天气卡片一、前言天气信息对户外徒步非常重要。本文实现一个天气卡片组件展示当前位置的天气状况包括温度、天气图标、空气质量等。二、天气数据模型interface WeatherData { temperature: number; // 当前温度(°C) high: number; // 最高温 low: number; // 最低温 condition: string; // 天气状况晴/多云/雨等 icon: string; // 天气图标 humidity: number; // 湿度(%) windSpeed: number; // 风速(km/h) aqi: number; // 空气质量指数 aqiLevel: string; // 空气质量等级 }三、天气卡片组件Component struct WeatherCard { Prop weather: WeatherData { temperature: 22, high: 26, low: 18, condition: 晴, icon: ☀️, humidity: 45, windSpeed: 15, aqi: 55, aqiLevel: 良, }; build() { Row() { // 左侧温度 天气图标 Column() { Text(this.weather.icon) .fontSize(40); Text(${this.weather.temperature}°C) .fontSize(28) .fontWeight(FontWeight.Bold); Text(this.weather.condition) .fontSize(14) .fontColor(#666); } .alignItems(HorizontalAlign.Center); // 右侧详细信息 Column() { Text(${this.weather.high}° / ${this.weather.low}°) .fontSize(16); Row() { this.InfoChip(, ${this.weather.humidity}%); this.InfoChip(, ${this.weather.windSpeed}km/h); this.InfoChip(️, this.weather.aqiLevel); } .margin({ top: 8 }); } .layoutWeight(1) .alignItems(HorizontalAlign.End); } .width(100%) .padding(16) .backgroundColor(#E3F2FD) .borderRadius(16); } Builder InfoChip(icon: string, text: string) { Row() { Text(icon).fontSize(12); Text(text).fontSize(12).fontColor(#666).margin({ left: 3 }); } .padding({ left: 8, right: 8, top: 4, bottom: 4 }) .backgroundColor(rgba(255,255,255,0.6)) .borderRadius(12) .margin({ left: 4 }); } }四、获取天气数据async function fetchWeather(lat: number, lng: number): PromiseWeatherData { // 调用天气 API const response await apiService.request(/api/weather, GET, { lat, lng, }); if (response.code 200) { return response.data as WeatherData; } // 返回默认数据 return { temperature: 22, high: 26, low: 18, condition: 晴, icon: ☀️, humidity: 45, windSpeed: 15, aqi: 55, aqiLevel: 良, }; }五、集成到首页在首页的aboutToAppear中加载天气数据aboutToAppear(): void { this.loadWeather(); } async loadWeather(): Promisevoid { try { const weather await fetchWeather(39.908, 116.397); AppStorage.setOrCreate(currentWeather, weather); } catch (e) { console.error(加载天气失败); } }六、总结天气卡片是徒步 App 首页的重要组件为用户提供出行决策参考。通过组件化设计WeatherCard 可以灵活复用。下一篇文章将实现路线列表页使用 LazyForEach 优化长列表性能。下一篇预告鸿蒙原生开发手记徒步迹 - 路线列表页与LazyForEach