前言
在一個(gè)移動(dòng)App中,我們最常用的內(nèi)容展現(xiàn)形式就是列表。今天,我們嘗試用React Native完成對(duì)列表的開(kāi)發(fā)。
ListView
ListView作為一個(gè)React Native官方提供的控件,我們需要了解它的屬性。
dataSource
是列表的數(shù)據(jù)源,通常以一個(gè)數(shù)組的形式傳給ListView。
renderRow
是列表的表現(xiàn)層,我們可以獲得dataSource的單項(xiàng)數(shù)據(jù),然后用于單項(xiàng)渲染。
官方例子
import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View } from 'react-native';
class ListViewBasics extends Component {
// 初始化模擬數(shù)據(jù)
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([
'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
])
};
}
render() {
return (
<View style={{flex: 1, paddingTop: 22}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData}</Text>}
/>
</View>
);
}
}
// 注冊(cè)應(yīng)用(registerComponent)后才能正確渲染
// 注意:只把應(yīng)用作為一個(gè)整體注冊(cè)一次,而不是每個(gè)組件/模塊都注冊(cè)
AppRegistry.registerComponent('ListViewBasics', () => ListViewBasics);
我們可以看到官方例子的數(shù)據(jù)比較簡(jiǎn)單,就是一個(gè)字符串的數(shù)組,將它在構(gòu)造方法中,加入到state中。在render方法中,我們即可在renderRow中,渲染我們每項(xiàng)的界面。
自己的一個(gè)例子
需求:
請(qǐng)求https://facebook.github.io/react-native/movies.json,將返回?cái)?shù)據(jù)的電影列表顯示出來(lái)。
code
ListViewBisc.js
import React, { Component } from 'react';
import {
View,
ListView,
Text,
} from 'react-native';
class ListViewBisc extends Component {
constructor(props) {
super(props);
// Initial of data of ListView
this.state={
ds:new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
};
}
// Render ListView
render(){
if (this.props.movies) {
var dataSource = this.state.ds.cloneWithRows(this.props.movies);
return(
<View style={{flex: 1, paddingTop: 22}}>
<ListView
dataSource={dataSource}
renderRow={(movie) => <Text>{movie.title}</Text>}
/>
</View>
)
}else {
return <Text>Loading</Text>
}
}
}
export default ListViewBisc;
index.android.js
import React, { Component } from 'react';
import {
AppRegistry,
View,
} from 'react-native';
import ListViewBisc from '../AwesomeProject/App/widget/ListViewBisc'
import HttpClient from '../AwesomeProject/App/widget/HttpClient'
class HelloWorld extends Component {
render(){
return (
<Text>{this.state.title}</Text>
)
}
constructor(props) {
super(props);
this.state={
title:'loading',
};
var self = this;
var httpUrl = 'https://facebook.github.io/react-native/movies.json';
HttpClient.requestAsync(httpUrl , function(responseJson){
self.setState({
title:responseJson.title,
movies:responseJson.movies,
})
});
}
render() {
return (
<View style={{width:400 , height:1000}}>
<ListViewBisc movies={this.state.movies}></ListViewBisc>
</View>
);
}
}
AppRegistry.registerComponent('AwesomeProject', () => HelloWorld);
結(jié)合前面講到的state的作用,我們就不難理解。我們?cè)诰W(wǎng)絡(luò)的回調(diào)中修改state,然后在render方法中,將state中的movies以props的形式傳入<ListViewBisc>中。
然后在ListViewBisc中,將movie的title取出來(lái)展示。
至此,我們就走完了,從網(wǎng)絡(luò)請(qǐng)求到列表顯示的完整流程。
如有問(wèn)題,歡迎指正。