React Native天气应用:Weather-App-React-Native
    		       		warning:
    		            这篇文章距离上次修改已过442天,其中的内容可能已经有所变动。
    		        
        		                
                以下是一个简化的React Native天气应用的代码实例,展示了如何获取当前位置的天气信息。
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import * as Location from 'expo-location';
import axios from 'axios';
 
const WeatherApp = () => {
  const [location, setLocation] = useState(null);
  const [weather, setWeather] = useState(null);
 
  useEffect(() => {
    (async () => {
      let { status } = await Location.requestPermissionsAsync();
      if (status !== 'granted') {
        alert('Permission to access location was denied');
      }
 
      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
 
      const lat = location.coords.latitude;
      const lon = location.coords.longitude;
      const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=YOUR_API_KEY&units=metric`;
 
      const response = await axios.get(apiUrl);
      setWeather(response.data);
    })();
  }, []);
 
  if (!weather) {
    return <Text>Loading...</Text>;
  }
 
  return (
    <View style={styles.container}>
      <Text style={styles.weatherText}>
        It is {weather.main.temp}°C in {weather.name} and the weather is {weather.weather[0].description}.
      </Text>
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 10,
  },
  weatherText: {
    textAlign: 'center',
    fontSize: 18,
  },
});
 
export default WeatherApp;在这个例子中,我们使用了expo-location来获取用户的当前位置,然后使用OpenWeatherMap的API来获取天气信息。代码首先请求定位权限,然后获取当前位置并用它来查询天气。最后,它展示了一个简单的UI来显示天气信息。
注意:你需要替换YOUR_API_KEY为你自己的OpenWeatherMap API密钥,并确保你的应用已经安装了axios库。
评论已关闭