美文网首页
【笔记】3构建应用

【笔记】3构建应用

作者: 给点阳光 | 来源:发表于2019-05-11 21:34 被阅读0次

    3.1 搭建环境

    Homebrew,一个OSX系统的通用包管理工具,用来安装RN的相关依赖。

    //RN包管理器同时使用了node和watchman
    brew install node
    brew install watchman
    //flow是Facebook出品的一个类型检查库
    brew install flow
    //如果安装过程中遇到问题,可能需要更新brew和相关依赖包
    brew update
    brew upgrade
    //如果出现错误,你需要修复本地的brew安装程序
    brew doctor
    //使用RN命令行工具来创建一个新的应用,它会包含一个包含RN、iOS和Android的全新模版工程
    react-native init FirstProject
    

    3.2 创建一个应用

    创建新应用

    • iOS和Android目录包含了平台相关的开发模版。
    • 在上面的文件中,入口文件是index.js,此时index.js是平台的入口文件。入口文件可以做区分。
    • index.ios.js和index.android.js各个平台的文件入口,没有的话自己创建一个,React代码放在其中。

    iOS侧:
    AppDelegate.m文件声明根视图:

    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"FirstProject" launchOptions:launchOptions];
    

    RN库将所有的类名使用RCT作为前缀,也就是说,RACRootView就是一个React Native类。

    核心对象:RCTRootView
    loadApp的代码的含义大致如下:

    • 创建一个ReactRootView对象
    • 然后通过ReactRootView对象启动RN的应用
    • 最后将ReactRootView作为主界面

    为了使用FirstProject组件,需要我们在React中注册一个相同名字的组件。

    import { AppRegistry } from 'react-native';
    import App from './App';
    AppRegistry.registerComponent('FirstProject', () => App);
    
    3.2.1 第一阶段:简单接收用户输入并显示

    输入框中输入H,Text中显示View。(App.js)

    import React from 'react';
    import {
      StyleSheet,
      Text,
      View,
      TextInput
    } from 'react-native';
    
    
    export default class App extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          zip: ""
        }
      }
    
      _handleTextChange = event => {
        this.setState({
          zip: event.nativeEvent.text
        });
      };
    
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              You input {this.state.zip}.
            </Text>
            <TextInput style={styles.input}
              onSubmitEditing={this._handleTextChange} />
          </View>
        );
      }
    }
    

    上面代码主要做了一下一些工作:

    1. 添加zip(邮编信息)至组件的初始状态(state)中。通常这个操作放在构造方法中进行。
    2. 然后修改Text组件的内容为this.state.zip。
    3. 添加一个TextInput组件(允许用户输入文本的基础组件)。
    4. 在TextInput组件的属性(prop)中监听了onSubmitEditing事件,事件回调需要作为组件中的一个函数。。
    3.2.2 第二阶段:Mock展示天气数据

    首先编写天气预报组件Forecast.js

    import React from "react";
    import { StyleSheet, Text, View } from "react-native"
    
    export default class Forecast extends React.Component {
        render() {
            return (
                <View style={styles.container}>
                    <Text style={styles.bigText}>
                        {this.props.main}
                    </Text>
                    <Text style={styles.mainText}>
                        Current conditions:{this.props.description}
                    </Text>
                    <Text style={styles.bigText}>
                        {this.props.temp}°F
                    </Text>
                </View>
    
            )
        }
    }
    
    const styles = StyleSheet.create({
        container: { height: 130 },
        bigText: {
            flex: 2,
            fontSize: 20,
            textAlign: "center",
            margin: 10,
            color: "#FFFFFF"
        },
        mainText: { flex: 1, fontSize: 16, textAlign: "center", color: "#FFFFFF" }
    });
    

    然后,在state中mock一些数据,将Forecast组件引入到主组件(App.js)中去。

    mport React from 'react';
    import {
      StyleSheet,
      Text,
      View,
      TextInput
    } from 'react-native';
    import Forecast from "./Forecast"
    
    
    export default class App extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          zip: "",
          //mock forcast属性值
          forcast:{
            main:'Clouds',
            description:'few clouds',
            temp:45.7
          }
        }
      }
    
      _handleTextChange = event => {
        // console.log(event.nativeEvent.text);
        this.setState({
          zip: event.nativeEvent.text
        });
      };
    
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              You input {this.state.zip}.
            </Text>
            //属性可以随便加?
            <Forecast
            main={this.state.forcast.main}
            description={this.state.forcast.description}
            temp={this.state.forcast.temp}/>
            <TextInput style={styles.input}
              returnKeyType='go'
              onSubmitEditing={this._handleTextChange} />
          </View>
        );
      }
    }
    // 样式表,此处省略不写了,可自行补充
    
    3.2.3 第三阶段:从Web获取数据

    数据请求:http://api.openweathermap.org/data/2.5/weather?q=10001&units=imperial&APPID=bbeb34ebf60ad50f7893e7440a1e2b0b

    首先增加网络请求文件open_weather_map.js

    const WEATHER_API_KEY = "bbeb34ebf60ad50f7893e7440a1e2b0b";
    const API_STEM = "http://api.openweathermap.org/data/2.5/weather?";
    
    function zipUrl(zip) {
      return `${API_STEM}q=${zip}&units=imperial&APPID=${WEATHER_API_KEY}`;
    }
    
    function fetchForecast(zip) {
      return fetch(zipUrl(zip))
        .then(response => response.json())
        .then(responseJSON => {
          return {
            main: responseJSON.weather[0].main,
            description: responseJSON.weather[0].description,
            temp: responseJSON.main.temp
          };
        })
        .catch(error => {
          console.error(error);
        });
    }
    
    export default { fetchForecast: fetchForecast };
    

    然后在根目录文件中放入flowers.png
    最后整合文件

    import React from 'react';
    import {
      StyleSheet,
      Text,
      View,
      TextInput,
      ImageBackground
    } from 'react-native';
    import Forecast from "./Forecast"
    import OpenWeatheMap from './open_weather_map'
    
    
    export default class App extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          zip: "",
          forcast: null
        }
      }
    
      _handleTextChange = event => {
        // console.log(event.nativeEvent.text);
        let zip = event.nativeEvent.text;
        OpenWeatheMap.fetchForecast(zip).then(forecast => {
          this.setState({
            forecast: forecast
          });
        })
    
      };
    
      render() {
        let content = null;
        if (this.state.forecast !== null) {//forecast写成forcast,调试大半天,趴在莫名奇妙的地方
          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("./flowers.png")}
            resizeMode="cover"
            style={styles.backdrop}>
            <View style={styles.overlay}>
              <View style={styles.row}>
                <Text style={styles.mainText}>
                  Current weather for
                </Text>
    
                <View style={styles.zipContainer}>
                  <TextInput
                    style={[styles.zipCode, styles.mainText]}
                    onSubmitEditing={this._handleTextChange}
                    underlineColorAndroid="transparent"
                  />
                </View>
              </View>
              {content}
            </View>
            </ImageBackground>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: { flex: 1, alignItems: "center"},
      backdrop: { flex: 1, flexDirection: "column" },
      overlay: {
        paddingTop: 5,
        backgroundColor: "#000000",
        opacity: 0.5,
        flexDirection: "column",
        alignItems: "center"
      },
      row: {
        flexDirection: "row",
        flexWrap: "nowrap",
        alignItems: "flex-start",
        padding: 30
      },
      zipContainer: {
        height: 42,
        borderBottomColor: "#DDDDDD",
        borderBottomWidth: 1,
        marginLeft: 5,
        marginTop: 3
      },
      zipCode: { flex: 1, flexBasis: 1, width: 60, height: 24 },
      mainText: { fontSize: 16, color: "#FFFFFF" }
    });
    
    

    相关文章

      网友评论

          本文标题:【笔记】3构建应用

          本文链接:https://www.haomeiwen.com/subject/ezufaqtx.html