React Native網(wǎng)絡(luò)請求及UI展示

廢話不多說,先上代碼

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>
            正在加載電影數(shù)據(jù)......
            </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中導(dǎo)入Component組件,在RN的世界里,組件相當(dāng)于一個UI控件,App就是由各種Component組件組合在一起顯示出來的。
從react-native中導(dǎo)入客戶端開發(fā)所需的控件及樣式表

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變量聲明一個網(wǎng)絡(luò)請求的網(wǎng)址
2,定義一個樣式表,樣式表用來定義一組樣式,樣式中包括UI控件的width,height,marginTop,marginLeft等位置寬高屬性,color,backgroundColor顏色值,fontSize字體大小,textAlign對齊方式等,也可以設(shè)置布局方式flex: 1是擴展到父視圖的大小,如果是最外層則擴展到整個屏幕大小,flexDirection用于設(shè)置子UI是橫向布局row還是縱向布局column,justifyContent用于設(shè)置UI布局的方式是居中,還是左對齊,右對齊,還是分散對齊等,alignItems設(shè)置與主軸垂直方向的布局方式

class ReactNativeTest extends Component
{
    constructor(props) {
      super(props);
        
      this.state = {
        movies: null,
      };
    }

定義一個組件ReactNativeTest,此名字必須與工程名一致
props:(1)大多數(shù)組件在創(chuàng)建時要設(shè)置各種參數(shù),用于定制的這些參數(shù)就叫屬性props
(2)比如Image設(shè)置source={pic},pic為圖片網(wǎng)絡(luò)或本地路徑,比如自定義的屬性
(3)與state相比,props是在父組件中指定,并且一經(jīng)指定不可更改。
state:state是用來監(jiān)控狀態(tài)改變,進而自動刷新頁面的組件,我們將movies放入state中,表示從網(wǎng)絡(luò)加載數(shù)據(jù),數(shù)據(jù)返回后會觸發(fā)setState方法修改movies的內(nèi)容,這時候?qū)?yīng)UI監(jiān)控state的地方會自動刷新,重新執(zhí)行,達到UI刷新的目的。

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

render方法用于返回組件創(chuàng)建的UI對象,根據(jù)state的movies來判斷,如果movies沒有東西,則調(diào)用renderLoadingView方法返回loading界面。
如果movies中有內(nèi)容,則取出其中一個dic,傳入renderMovie方法,返回指定顯示內(nèi)容的UI界面

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

fetchData方法為RN的網(wǎng)絡(luò)請求方法,fetch傳入URL和GET請求,.then中將response返回轉(zhuǎn)為json,賦值給responseData,調(diào)用setState方法,給movies賦值,并捕獲異常進行回調(diào)。

componentDidMount()
    {
        this.fetchData();
    }

組件加載完畢后調(diào)用請求網(wǎng)絡(luò)的方法。

renderLoadingView()
    {
        return (
            <View style={styles.container}>
            <Text>
            正在加載電影數(shù)據(jù)......
            </Text>
            </View>
            );
    }

renderLoadingView方法返回加載中的界面,包括一個View,View中嵌套Text,Text相當(dāng)于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>
            );
    }
}

將網(wǎng)絡(luò)請求返回的movie傳進來,初始化對應(yīng)的View,Image,Text顯示圖片,文本信息。

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

注冊app組件,完成!棒棒的!

效果展示如下:


Paste_Image.png
Paste_Image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容