React Native 之 列表【ListView,NavigatorIOS】

React-Native最近看了下他的ListView组件,记录下自己实现的小小功能:

一个简单的列表都没啥特别的了,这里添加一个导航。

首先使用NavigatorIOS组件,给我们的首页添加一个导航

1
2
3
4
5
6
7
8
9
10
11
12
var WalkerfreeProject = React.createClass({
render:function(){
return (
<NavigatorIOS
style={styles.container}
initialRoute={{
'title':'Welcome',
'component': Movies,
}} />
);
}
});

如果只是就这么几行代码,还是有问题的,需要加一下样式

1
2
3
4
5
var styles = StyleSheet.create({
container: {
flex: 1,
}
});

最后组件注册

1
AppRegistry.registerComponent('WalkerfreeProject', () => WalkerfreeProject);

Movies这个就是一个ListView的组件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
var React = require('react-native');

var {
AppRegistry,
Image,
ListView,
StyleSheet,
Text,
View,
NavigatorIOS,
ScrollView,
Navigator
} = React;

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

var Movies = React.createClass({
getInitialState:function(){
return {
dataSource:new ListView.DataSource({
rowHasChanged:(row1, row2) => row1 != row2
}),
loaded:false
}
},
componentDidMount:function(){
this.fetchData();
},
fetchData:function(){
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource:this.state.dataSource.cloneWithRows(responseData.movies),
loaded:true
});
})
.done()
},
renderLoadingView:function(){
return (
<View style={styles.container}>
<Text>
Loading Views
</Text>
</View>
);
},
renderMovie:function(movie){
return (
<View style={styles.container} key={movie.id}>
<Image
source={{uri:movie.posters.thumbnail}}
style={styles.thumbnail} />
<View style={styles.rightContainer}>
<Text style={styles.title} numberOfLines={1}>
{movie.title}
</Text>
<Text style={styles.year}>
{movie.year}
</Text>
</View>
<View style={styles.separator}></View>
</View>
);
},
render: function() {
if(!this.state.loaded){
return this.renderLoadingView();
}

return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView} />
);
}
});

var styles = StyleSheet.create({
separator: {
height: 1,
backgroundColor: '#CCCCCC',
},
listView:{
marginTop:65,
},
container: {
flex: 1,
},
thumbnail: {
width: 53,
height: 81,
},
rightContainer:{
flex:1,
position:'absolute',
top:0,
left:55
},
title:{
fontSize:20,
marginBottom:8,
textAlign:'left',
width:260
},
year:{
textAlign:'center'
}
});

module.exports = Movies;

整个代码就贴到这里了,没有啥需要说明的。这个官网也是有的,只是注意一下这里的样式就好了。当然在index.ios.js的里面要引入

1
var Movies = require('./App/Movies');

这个我是他Movies添加到了App这个目录里了,所以需要自己引入一下。其实也还是蛮简单的,因为就是一个简单的例子而已