React Native网络请求及UI展示

708 查看

废话不多说,先上代码

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

var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';

const styles = StyleSheet.create({
    container:{
        flex:1,flexDirection:'row',justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'
    },
    thumbnail:{
        width:100,height:80
    },
    rightContainer:{
        flex:1
    },
    title:{
        fontSize:20,marginBottom:8,textAlign:'center'
    },
    year:{
        textAlign:'center'
    },
});

class ReactNativeTest extends Component
{
    constructor(props) {
      super(props);

      this.state = {
          movies: null,
      };
    }

    render()
    {
        if (!this.state.movies) {
            return this.renderLoadingView();
        }
        var movie = this.state.movies[0];
        return this.renderMovie(movie);
    }

    fetchData()
    {
        fetch(REQUEST_URL, {
            method: 'GET'
        })
        .then((response) => response.json())
        .then((responseData) => {
            this.setState({
                movies:responseData.movies,
            });
        })
        .catch((error) => {
                callback(error);
        });
    }

    componentDidMount()
    {
        this.fetchData();
    }

    renderLoadingView()
    {
        return (
            <View style={styles.container}>
            <Text>
            正在加载电影数据......
            </Text>
            </View>
            );
    }

    renderMovie(movie)
    {
        return (
            <View style={styles.container}>
                <Image source={{uri:movie.posters.thumbnail}}
                style={styles.thumbnail} />
                <View style={styles.rightContainer}>
                    <Text style={styles.title}>{movie.title}</Text>
                    <Text style={styles.year}>{movie.year}</Text>
                </View>
            </View>
            );
    }
}

AppRegistry.registerComponent('ReactNativeTest', () => ReactNativeTest);

讲解:

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

从react中导入Component组件,在RN的世界里,组件相当于一个UI控件,App就是由各种Component组件组合在一起显示出来的。
从react-native中导入客户端开发所需的控件及样式表

var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';

const styles = StyleSheet.create({
    container:{
        flex:1,flexDirection:'row',justifyContent:'center',alignItems:'center',backgroundColor:'#F5FCFF'
    },
    thumbnail:{
        width:100,height:80
    },
    rightContainer:{
        flex:1
    },
    title:{
        fontSize:20,marginBottom:8,textAlign:'center'
    },
    year:{
        textAlign:'center'
    },
});

1,用var变量声明一个网络请求的网址
2,定义一个样式表,样式表用来定义一组样式,样式中包括UI控件的width,height,marginTop,marginLeft等位置宽高属性,color,backgroundColor颜色值,fontSize字体大小,textAlign对齐方式等,也可以设置布局方式flex: 1是扩展到父视图的大小,如果是最外层则扩展到整个屏幕大小,flexDirection用于设置子UI是横向布局row还是纵向布局column,justifyContent用于设置UI布局的方式是居中,还是左对齐,右对齐,还是分散对齐等,alignItems设置与主轴垂直方向的布局方式

class ReactNativeTest extends Component
{
    constructor(props) {
      super(props);

      this.state = {
          movies: null,
      };
    }

定义一个组件ReactNativeTest,此名字必须与工程名一致
props:(1)大多数组件在创建时要设置各种参数,用于定制的这些参数就叫属性props
(2)比如Image设置source={pic},pic为图片网络或本地路径,比如自定义的属性
(3)与state相比,props是在父组件中指定,并且一经指定不可更改。
state:state是用来监控状态改变,进而自动刷新页面的组件,我们将movies放入state中,表示从网络加载数据,数据返回后会触发setState方法修改movies的内容,这时候对应UI监控state的地方会自动刷新,重新执行,达到UI刷新的目的。

render()
    {
        if (!this.state.movies) {
            return this.renderLoadingView();
        }
        var movie = this.state.movies[0];
        return this.renderMovie(movie);
    }

render方法用于返回组件创建的UI对象,根据state的movies来判断,如果movies没有东西,则调用renderLoadingView方法返回loading界面。
如果movies中有内容,则取出其中一个dic,传入renderMovie方法,返回指定显示内容的UI界面

fetchData()
    {
        fetch(REQUEST_URL, {
            method: 'GET'
        })
        .then((response) => response.json())
        .then((responseData) => {
            this.setState({
                movies:responseData.movies,
            });
        })
        .catch((error) => {
                callback(error);
        });
    }

fetchData方法为RN的网络请求方法,fetch传入URL和GET请求,.then中将response返回转为json,赋值给responseData,调用setState方法,给movies赋值,并捕获异常进行回调。

componentDidMount()
    {
        this.fetchData();
    }

组件加载完毕后调用请求网络的方法。

renderLoadingView()
    {
        return (
            <View style={styles.container}>
            <Text>
            正在加载电影数据......
            </Text>
            </View>
            );
    }

renderLoadingView方法返回加载中的界面,包括一个View,View中嵌套Text,Text相当于iOS中的label

renderMovie(movie)
    {
        return (
            <View style={styles.container}>
                <Image source={{uri:movie.posters.thumbnail}}
                style={styles.thumbnail} />
                <View style={styles.rightContainer}>
                    <Text style={styles.title}>{movie.title}</Text>
                    <Text style={styles.year}>{movie.year}</Text>
                </View>
            </View>
            );
    }
}

将网络请求返回的movie传进来,初始化对应的View,Image,Text显示图片,文本信息。

AppRegistry.registerComponent('ReactNativeTest', () => ReactNativeTest);

注册app组件,完成!棒棒的!

效果展示如下:


Paste_Image.png

Paste_Image.png