本节主要说的是一个基于React-Native的天气APP,通过本案例的练习,可以初步的了解React Native的基本使用方法。
整体的软件构架如下图所示:
修改后的项目入口文件如下:
import {AppRegistry} from 'react-native'; import {name as appName} from './app.json'; import WeatherHome from "./src/weather/WeatherHome"; AppRegistry.registerComponent(appName, () => SimpleList);新建天气主页面 WeatherHome.js 文件,文件主要内容如下:
import React, { Component } from 'react'; import { StyleSheet, View, Text, ImageBackground, TextInput, Dimensions, } from 'react-native'; import Forecast from "./Forecast"; import WeatherData from "./WeatherData"; export default class WeatherHome extends Component { constructor(props) { super(props); this.state = {zip:"",forecast: null}; } _handleTextChange = event => { let zip = event.nativeEvent.text; console.log('邮政编码'+ zip); WeatherData.fetchForecast(zip).then(forecast =>{ console.log(forecast); this.setState({forecast:forecast}); }); }; render() { let content = null; if(this.state.forecast != null){ content = ( <Forecast main = {this.state.forecast.main} description = {this.state.forecast.description} temp = {this.state.forecast.temp} /> ); } return ( <View style = {styles.container}> <ImageBackground source={require("./../../assets/img/weather.jpeg")} resizeMode="cover" style={styles.backdrop} > <View style = {styles.weather_layout}> <View style = {styles.city_info}> <Text style={styles.welcome}> 城市:{this.state.zip} </Text> <TextInput style = {styles.input} onSubmitEditing={this._handleTextChange} underlineColorAndroid="transparent" > </TextInput> </View> {content} </View> </ImageBackground> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center" }, city_info:{ flexDirection: 'row', width:Dimensions.get('window').width }, weather_layout:{ paddingTop: 5, backgroundColor: "#000000", opacity: 0.5, flexDirection: "column", alignItems: "center" }, backdrop:{ flex: 1, flexDirection: "column", width: Dimensions.get('window').width, }, welcome:{ fontSize:20, textAlign:"center", margin:10 }, input:{ fontSize: 30, padding: 2, height: 50, textAlign: "center", color: "#ffffff" } });新建天气主页面 Forecast.js 文件,文件主要内容如下:
import React, {Component} from 'react' import { StyleSheet, View, Text } from 'react-native'; export default class Forecast extends Component{ render() { return ( <View style = {styles.container}> <Text style = {styles.bigText}> {this.props.main} </Text> <Text style = {styles.mainText}> 此刻天气状态:{this.props.description} </Text> <Text style = {styles.bigText}> 温度:{this.props.temp} F </Text> </View> ); } } const styles = StyleSheet.create({ container:{ height: 180 }, mainText:{ flex: 1, fontSize: 20, textAlign: "center", color: "#FFFFFF" }, bigText:{ flex: 2, fontSize: 20, textAlign: "center", margin: 10, color: "#FFFFFF" } });关注微信公众号“AI Technology Space”,回复“WeatherDemo”下载源代码哦,感谢大家的支持!