React Native 學習指南(二) - 天氣小項目實戰演練

概述

經過上一篇咱們已經經過命令行工具構建了第一個 React Native 應用,並在 iOS 設備中成功運行,熟悉了工程的文件代碼組織結構。咱們將繼續使用該工程來開發一個天氣應用,以此初步創建對 StyleSheetflexbox用戶輸入組件添加網絡訪問 等概念的理解。javascript

建立 WeatherMain.js 並移動默認組件代碼

WeatherMain.jscss

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class WeatherMain extends Component {
  render() {
    return (
      <View style={styles.container}> <Text style={styles.welcome}> Welcome to Hello RN Weather ! </Text> </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});複製代碼

精簡 index.ios.jsindex.ios.js前端

import { AppRegistry } from 'react-native'
import WeatherMain from './WeatherMain'

AppRegistry.registerComponent('HelloRNWeather', () => WeatherMain);複製代碼

更改 AppDelegate 中根視圖組件 moduleNamejava

RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"HelloRNWeather"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];複製代碼

此時,確保項目從新啓動可正常運行。react

處理用戶輸入

添加一個輸入框,以便用戶可經過輸入郵編來獲取對應地區的天氣ios

render 函數前添加一段處理生命週期的代碼git

constructor(props) {
    super(props)
    this.state = {
        zip: ''
    }
}複製代碼

修改顯示內容爲郵編github

<Text style={styles.welcome}>
     地區郵編: {this.state.zip}
</Text>複製代碼

添加 TextInput 輸入框組件,並監聽輸入事件objective-c

<TextInput style={styles.input} onSubmitEditing={(event) => this._handleInputTextDidChanged(event)}/>複製代碼

styles 中添加新的 input 樣式json

input: {
  fontSize: 20,
  borderWidth: 3,
  height: 44,
}複製代碼

添加事件監聽回調函數

_handleInputTextDidChanged(event) {
    this.setState({zip: event.nativeEvent.text});
}複製代碼

記得更新導入語句

import {
  ...
  TextInput,
  ...
} from 'react-native';複製代碼

在 iOS 模擬器運行項目,如今能夠成功顯示輸入的內容了

處理用戶輸入

展示數據

mock 一些天氣數據

constructor(props) {
    super(props);

    this.state = {
        zip: '',
        forecast: {
            main: 'Snow',
            description: 'very cold',
            temp: 3
        }
    }
}複製代碼

建立 Forecast.js做爲天氣預報組件

import React, {Component} from 'react'
import {
  StyleSheet,
  Text,
  View,
} from 'react-native'

export default class Forecast extends Component {
  render() {
    return (
      <View> <Text style={styles.bigText}> {this.props.main} </Text> <Text style={styles.mainText}> {this.props.description} </Text> <Text style={styles.bigText}> {this.props.temp} ℃ </Text> </View>
    )
  }
}

const styles = StyleSheet.create({
  bigText: {
    flex: 2,
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: '#374256'
  },
  mainText: {
    flex: 1,
    fontSize: 16,
    textAlign: 'center',
    color: '#374256'
  }
})複製代碼

Forecast 組件添加到 WeatherMain

import Forecast from './Forecast' // 導入 Forecast 

    <View style={styles.container}>
       ......
       <Forecast main={this.state.forecast.main} description={this.state.forecast.description} temp={this.state.forecast.temp}/>
       ......
    </View>複製代碼

添加完成後,iOS 模擬器 Command + R 便可看到以前mock的數據展示出來了,至於美觀上的問題,接下來專門摸索樣式佈局的時候再來慢慢解決。

展示數據

添加背景圖片

將資源文件放入工程目錄

導入 Image 組件

import {
  ...
  Image,
  ...
} from 'react-native';複製代碼

Image 組件做爲容器使用添加到視圖中

<Image source={require("./background.jpg")} resizeMode='cover' style={styles.background}>
    <View style={styles.overlay}> <Text style={styles.welcome}> 地區郵編: {this.state.zip} </Text> <TextInput style={styles.input} onSubmitEditing={(event) => this._handleInputTextDidChanged(event)}/> <Forecast main={this.state.forecast.main} description={this.state.forecast.description} temp={this.state.forecast.temp}/> </View> </Image>複製代碼

刷新便可看到添加的背景圖片了,固然了,仍然仍是醜,後面咱們再慢慢來解決樣式佈局問題,感受前端的佈局確實和 AutoLayout 很不同啊~ /無奈攤手

React Native 添加背景圖片

獲取網絡數據

接下來,咱們將嘗試經過網絡訪問來用真實數據來替換以前的 mock 數據。

React Native 中的 fetch 接口基於 Promise 語法風格

fetch('http://wthrcdn.etouch.cn/weather_mini?citykey=101010100')
  .then((response) => response.json())
  .then((responseJSON) => {
     // handle Response
  })
  .catch((error) => {
     console.warn(error);
  })複製代碼

render 中更新渲染邏輯

render() {
  var content = null;
  if (this.state.forecast !== null) {
     content = <Forecast main={this.state.forecast.main} description={this.state.forecast.description} temp={this.state.forecast.temp}/>; } ...... }複製代碼

使用網絡訪問替代 mock 數據

this.state = {
    zip: '',
    forecast: null
};
fetch('http://wthrcdn.etouch.cn/weather_mini?citykey=101010100')
    .then((res) => {
    return res.json()
    })
    .then((responseJSON) => {
        this.setState({
        forecast: {
          main: responseJSON.data.forecast[0].type,
          description: responseJSON.data.ganmao,
          temp: responseJSON.data.wendu,
        }
     });
    })
    .catch((error) => {
      console.warn(error);
    })複製代碼

刷新就能看到北京的真實天氣了

React-Native 網絡訪問

== 若出現網絡錯誤,是由於蘋果 iOS 9 起再也不支持http協議,須要對特定域名進行額外處理。 ==

Info.plist 文件

總結

這樣下來,咱們就對 StyleSheetflexbox用戶輸入組件添加網絡訪問 等概念都有基本的認識,也完成了一個能顯示實時天氣的小應用了。不過它如今還很簡陋、也不美觀,接下來咱們將在進一步認識移動應用組件後再對樣式佈局進行優化。

操練代碼:Binlogo/HelloReactNative - Github

相關文章
相關標籤/搜索