- 本文是參照http://reactnative.cn/docs/0.42/sample-application-movies.html 寫作
1齿诉,第一步模擬一下數(shù)據(jù)先,你可以把它放在index.ios.js和index.android.js的任意位置
var MOCKED_MOVIES_DATA = [
{title: '標題', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}},
];
2,第二步,需要用到的React Native包和組件
import React, {
Component,
} from 'react';
import {
AppRegistry,
Image,
StyleSheet,
Text,
View,
} from 'react-native';
3,第三步在render函數(shù)中
render() {
var movie = MOCKED_MOVIES_DATA[0];
return (
<View style={styles.container}>
<Image source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}></View>
<Text>{movie.title}</Text>
<Text>{movie.year}</Text>
</View>
);
}
4,第四步設置樣式
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
flexDirection:"row",
},
thumbnail: {
width: 53,
height: 81,
},
rightContainer: {
flex:1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
});
在模擬器或者真機上就可以查看到這樣的效果圖
5,第五步间唉,拉取真實數(shù)據(jù)
A,請求鏈接
/***
* 拉取真實數(shù)據(jù)(網(wǎng)絡JSON數(shù)據(jù))
*/
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
B,首先在應用中創(chuàng)建一個初始的null狀態(tài),這樣可以通過this.state.movies == null來判斷我們的數(shù)據(jù)是不是已經(jīng)被抓取到了月弛。我們在服務器響應返回的時候執(zhí)行this.setState({movies: moviesData})來改變這個狀態(tài)弦叶。把下面這段代碼放到我們的React類的render函數(shù)之前
constructor(props) {
super(props); //這一句不能省略,照抄即可
this.state = {
movies: null //這里放你自己定義的state變量及初始值
};
// 在ES6中,如果在自定義的函數(shù)里使用了this關(guān)鍵字贤惯,則需要對其進行“綁定”操作洼专,否則this的指向不對
// 像下面這行代碼一樣,在constructor中使用bind是其中一種做法(還有一些其他做法孵构,如使用箭頭函數(shù)等)
this.fetchData = this.fetchData.bind(this);
}
C屁商,組件加載完畢之后,就可以向服務器請求數(shù)據(jù)颈墅。componentDidMount是React組件的一個生命周期方法蜡镶,它會在組件剛加載完成的時候調(diào)用一次,以后不會再被調(diào)用恤筛。
componentDidMount() {
this.fetchData();
}
D,現(xiàn)在我們來為組件添加fetchData函數(shù)官还。你所需要做的就是在Promise調(diào)用鏈結(jié)束后執(zhí)行this.setState({movies:data})。在React的工作機制下毒坛,setState實際上會觸發(fā)一次重新渲染的流程妻枕,此時render函數(shù)被觸發(fā),發(fā)現(xiàn)this.state.movies不再是null粘驰。
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
// 注意屡谐,這里使用了this關(guān)鍵字,為了保證this在調(diào)用時仍然指向當前組件蝌数,我們需要對其進行“綁定”操作
this.setState({
movies: responseData.movies,
});
});
}
E,現(xiàn)在我們來修改render函數(shù)愕掏。在電影數(shù)據(jù)加載完畢之前,先渲染一個“加載中”的視圖顶伞;而如果電影數(shù)據(jù)已經(jīng)加載完畢了饵撑,則渲染第一個電影數(shù)據(jù)。
render() {
if (!this.state.movies) {
return this.renderLoadingView();
}
var movie = this.state.movies[0];
return this.renderMovie(movie);
}
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>
);
}
效果如下
6唆貌,問題來了滑潘,電影不可能只有一部電影吧。所以需要用到一個新的組件ListView組件锨咙。(至于為什么用ListView組件而不用ScrollView組件语卤。原因是把內(nèi)容放到ListView里,比起直接渲染出所有的元素酪刀,或是放到一個ScrollView組件要好粹舵,這是因為盡管React很高效,渲染一個可能很大的元素列表還是會很慢骂倘。ListView會安排視圖的渲染眼滤,只顯示當前在屏幕上的那些元素。而那些已經(jīng)渲染好了但移動到了屏幕之外的元素历涝,則會從原生視圖結(jié)構(gòu)中移除<以提高性能>诅需。)
A,添加組件ListView
import {
AppRegistry,
Image,
ListView,
StyleSheet,
Text,
View,
} from 'react-native';
B,現(xiàn)在來修改render函數(shù)漾唉。當我們已經(jīng)有了數(shù)據(jù)之后,渲染一個包含多個電影信息的ListView堰塌,而不僅僅是單個的電影赵刑。
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
//dataSource接口用來在ListView的整個更新過程中判斷哪些數(shù)據(jù)行發(fā)生了變化。
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
styles={styles.listView}
/>
);
}
C,在B中你會注意到我現(xiàn)在用到了this.state中的dataSource蔫仙。下一步就是在constructor生成的初始狀態(tài)中添加一個空白的dataSource。另外丐箩,我們現(xiàn)在要把數(shù)據(jù)存儲在dataSource中了摇邦,所以不再另外用this.state.movies來保存數(shù)據(jù)。我們可以在state里用一個布爾型的屬性(this.state.loaded)來判斷數(shù)據(jù)加載是否已經(jīng)完成了屎勘。
constructor(props) {
super(props); //這一句不能省略施籍,照抄即可
this.state = {
dataSource : new ListView.DataSource({
rowHasChanged:(row1,row2) =>row1 !== row2,
}),
loaded:false,
};
// 在ES6中,如果在自定義的函數(shù)里使用了this關(guān)鍵字概漱,則需要對其進行“綁定”操作丑慎,否則this的指向不對
// 像下面這行代碼一樣,在constructor中使用bind是其中一種做法(還有一些其他做法瓤摧,如使用箭頭函數(shù)等)
this.fetchData = this.fetchData.bind(this);
}
D,同時我們也要修改fetchData方法來把數(shù)據(jù)更新到dataSource里
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
// 注意竿裂,這里使用了this關(guān)鍵字,為了保證this在調(diào)用時仍然指向當前組件照弥,我們需要對其進行“綁定”操作
this.setState({
dataSource:this.state.dataSource.cloneWithRows(responseData.movies),
loaded:true,
});
});
}
E,最后添加組件樣式
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
最終效果
最后附上源碼
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
Image,
ListView,
StyleSheet,
Text,
View,
} from 'react-native';
/***
* 拉取真實數(shù)據(jù)(網(wǎng)絡JSON數(shù)據(jù))
*/
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
export default class RNDemo extends Component {
//首先在應用中創(chuàng)建一個初始的null狀態(tài)腻异,這樣可以通過this.state.movies == null來判斷我們的數(shù)據(jù)是不是已經(jīng)被抓取到了。我們在服務器響應返回的時候執(zhí)行this.setState({movies: moviesData})來改變這個狀態(tài)这揣。把下面這段代碼放到我們的React類的render函數(shù)之前
constructor(props) {
super(props); //這一句不能省略悔常,照抄即可
this.state = {
dataSource : new ListView.DataSource({
rowHasChanged:(row1,row2) =>row1 !== row2,
}),
loaded:false,
};
// 在ES6中,如果在自定義的函數(shù)里使用了this關(guān)鍵字给赞,則需要對其進行“綁定”操作机打,否則this的指向不對
// 像下面這行代碼一樣,在constructor中使用bind是其中一種做法(還有一些其他做法片迅,如使用箭頭函數(shù)等)
this.fetchData = this.fetchData.bind(this);
}
//組件加載完畢之后残邀,就可以向服務器請求數(shù)據(jù)。componentDidMount是React組件的一個生命周期方法柑蛇,它會在組件剛加載完成的時候調(diào)用一次罐旗,以后不會再被調(diào)用。
componentDidMount() {
this.fetchData();
}
//現(xiàn)在我們來為組件添加fetchData函數(shù)唯蝶。你所需要做的就是在Promise調(diào)用鏈結(jié)束后執(zhí)行this.setState({movies:data})九秀。在React的工作機制下,setState實際上會觸發(fā)一次重新渲染的流程粘我,此時render函數(shù)被觸發(fā)鼓蜒,發(fā)現(xiàn)this.state.movies不再是null痹换。
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
// 注意,這里使用了this關(guān)鍵字都弹,為了保證this在調(diào)用時仍然指向當前組件娇豫,我們需要對其進行“綁定”操作
this.setState({
dataSource:this.state.dataSource.cloneWithRows(responseData.movies),
loaded:true,
});
});
}
//你會注意到我們現(xiàn)在用到了this.state中的dataSource。下一步就是在constructor生成的初始狀態(tài)中添加一個空白的dataSource畅厢。另外冯痢,我們現(xiàn)在要把數(shù)據(jù)存儲在dataSource中了,所以不再另外用this.state.movies來保存數(shù)據(jù)框杜。我們可以在state里用一個布爾型的屬性(this.state.loaded)來判斷數(shù)據(jù)加載是否已經(jīng)完成了浦楣。
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
//dataSource接口用來在ListView的整個更新過程中判斷哪些數(shù)據(jù)行發(fā)生了變化。
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
styles={styles.listView}
/>
);
}
renderLoadingView() {
return(
<View style={styles.container}>
<Text>
Loading movies...
</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>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
flexDirection:"row",
},
thumbnail: {
width: 53,
height: 81,
},
rightContainer: {
flex:1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
listView:{
paddingTop:20,
backgroundColor:'#F5FCFF',
},
});
AppRegistry.registerComponent('RNDemo', () => RNDemo);