本文基于React Native 0.52
http://www.cnblogs.com/MaiJiangDou/p/8351288.html
Demo上传到Git了,有需要可以看看,写了新内容会上传的。Git地址 https://github.com/gingerJY/React-Native-Demo
一、总览
这个效果也是APP里很常见的,之前把这个想的太复杂了,后来才知道原来用FlatList就可以轻松实现,效果图如下(专题精选):
二、代码实现
1、加几条数据
1
2
3
4
5
6
7
8
9
10
11
12
|
topic: [
{
title:
'岁末清扫有它们,体验大不同'
,
describe:
'更轻松、更美好的大扫除攻略'
,
price:
'9.9元起'
,
},
{
title:
'新年一点红,幸运一整年'
,
describe:
'那些让你“红”运当头的好物'
,
price:
'9.9元起'
,
},
]
|
2、写列表的一个item
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
renderTopicItem = ({ item }) => {
return
(
<TouchableOpacity style={styles.topicItem}>
<Image source={require(
'../../img/topic.jpg'
)} style={styles.topicImg} />
<View style={styles.topicContainer}>
<View style={styles.topicText}>
<Text style={styles.topicTitle}>{item.title}</Text>
<Text style={styles.topicDesc}>{item.describe}</Text>
</View>
<Text style={styles.topicPrice}>{item.price}</Text>
</View>
</TouchableOpacity>
)
}
|
3、用FlatList渲染出列表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
renderTopic() {
return
(
<View style={styles.topic}>
<Text style={styles.topicHead}>专题精选</Text>
<FlatList
data={
this
.state.topic}
keyExtractor={(item, index) => index}
renderItem={
this
.renderTopicItem}
horizontal={
true
}
showsHorizontalScrollIndicator={
false
}
/>
</View>
)
}
|
-
- data —— 数据(目前只支持普通数组)
- renderItem —— 根据行数据data渲染每一行的组件
-
keyExtractor —— 用于为给定的item生成一个不重复的key(Key的作用是使React能够区分同类元素的不同个体,以便在刷新时能够确定其变化的位置,减少重新渲染的开销)
- horizontal —— 设为true时是水平布局
- showsHorizontalScrollIndicator —— 设为false,则不显示水平滚动条
4、样式
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
|
topic: {
width: width,
alignItems:
'center'
,
backgroundColor:
'#fff'
,
paddingBottom:10,
marginBottom:10,
},
topicHead:{
fontSize:16,
color:
'#666'
,
padding:15,
},
topicItem: {
width: width*0.7,
marginLeft:15,
},
topicImg: {
width: width*0.7,
height: width*0.4,
borderWidth:0.5,
borderColor:
'#cdcdcd'
,
borderRadius:2,
},
topicContainer:{
flexDirection:
'row'
,
justifyContent:
'space-between'
,
marginTop:10,
},
topicTitle:{
fontSize:16,
color:
'#666'
,
},
topicDesc:{
fontSize:13,
color:
'#999'
,
marginTop:3,
},
topicPrice:{
fontSize:14,
color:
'#b4282d'
,
},
|
recommend.js完整代码 https://github.com/gingerJY/example/blob/master/RN_flatList/recommend.js
三、其他
这种也是用 FlatList 做的,写法都差不多,具体看https://github.com/gingerJY/React-Native-Demo