今天來講的是最常使用的 List 系列了
這就次以 FlatList 當主角吧
他是在 0.43 之後才出現的「進化版 ListView」
剛開始學習 React Native 的我
第一次就使用到「進化」的版本,多少會自我感覺良好 ((什麼奇怪的感覺…
廢話不多說
我就開始照著官方給的範例,一步一步的做囉
點我看官方範例
最重要的有三大重點
第一、
資料的結構與來源
首先,我們先設好三個客戶的假資料
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
constructor(props) {
super(props);
this.CustomerInformationModule=NativeModules.CustomerInformationModule;
this._goBack = this._goBack.bind(this);
this._renderListView = this._renderListView.bind(this);
this.state = {
data:[
{name: 'Devin0',phone:'98980798'},
{name: 'Devin1',phone:'19898798'},
{name: 'Devin2',phone:'59898798'},
],
};
}
|
第二、
把資料帶給 FlatList
並且給 renderItem 一個產生 view 的 function
1
2
3
4
|
<FlatList
data={this.state.data}
renderItem={this._renderListView}
/>
|
第三、
寫好 _renderListView 並 return 我們想要的 view
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
_renderListView(item){
return(
<View style={{flex: 1, flexDirection: 'column'}}>
<Image
source={{uri: 'ci_info_background'}}
style={styles.topImage}
resizeMode="contain">
<Text style={styles.topText}>顏阿澤</Text>
<Text style={styles.topText}>80005455</Text>
</Image>
<View style = {styles.container}>
<View style={styles.infoContainer}>
<Text style={styles.titleText}>客户名字 </Text>
<Text style={styles.infoText}>{item.name}</Text>
</View>
<View style={styles.infoContainer}>
<Text style={styles.titleText}>客戶電話 </Text>
<Text style={styles.infoText}>{item.phone}</Text>
</View>
</View>
</View>
)
}
|
好的,到此為止,一切都很順利
萬事俱備,就差 run 出來了
可是沒想到,run 出來的結果並不是我們想的樣子
{item.name} && {item.phone} 這兩個參數給的是空值
也就是說我客戶的姓名與電話是空白的
可是為什麼會這樣呢?
官方的範例中和資料有關係的也只有 data = { this.props.data } 這一行
給完資料就直接給 renderItem 畫 view
也沒看到有哪一行 code 是綁資料給 _renderItem 這個 function 的呀
在經過一番 Google 之後毫無所獲
最後還是在官方的文檔上找到了解答
原來 renderItem 這個 function 系統會自動傳入一個參數
而這個參數是經過一層包裝的
我們的資料就包在 info 這個 object 之中
所以我把 code 改成了下面這樣
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
|
_renderListView(mInfo){
var customer = mInfo.item;
return(
<View style={{flex: 1, flexDirection: 'column'}}>
<Image
source={{uri: 'ci_info_background'}}
style={styles.topImage}
resizeMode="contain">
<Text style={styles.topText}>顏阿澤</Text>
<Text style={styles.topText}>80005455</Text>
</Image>
<View style = {styles.container}>
<View style={styles.infoContainer}>
<Text style={styles.titleText}>客户名字 </Text>
<Text style={styles.infoText}>{customer.name}</Text>
</View>
<View style={styles.infoContainer}>
<Text style={styles.titleText}>客戶電話 </Text>
<Text style={styles.infoText}>{customer.phone}</Text>
</View>
</View>
</View>
)
}
|
可以看到我給 _renderListview 一個 mInfo 的參數
再從 mInfo 提取資料出來給變數 customer
這樣我們就可以從 customer 裡面得到想要的資料囉
大家快去試試吧
資料來源:
http://reactnative.cn/docs/0.47/flatlist.html#content