列表視圖 ListView
ListView 是一個特殊的 ScrollView矾兜,用來展示一個縱向排列結(jié)構(gòu)相似的內(nèi)容。
ListView 可以高效地處理大量數(shù)據(jù)焕刮,它不像 ScrollView 將所有包含其中的組件都渲染出來墙杯,它只會渲染當前會顯示在屏幕上的內(nèi)容。
ListView 組件創(chuàng)建時需要設(shè)置兩個屬性:
-
dataSource
:列表視圖顯示內(nèi)容的數(shù)據(jù)源高镐。 -
renderRow
:渲染每行內(nèi)容的方法。
下面展示一個實例:
import React, { Component } from 'react';
import {
AppRegistry,
ListView,
Text,
View
} from 'react-native';
export default class HelloWorld extends Component {
// Initialize the hardcoded data
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>
);
}
}
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
這個例子中观腊,先創(chuàng)建一個 ListView.DataSource
,在創(chuàng)建時梧油,需要提供一個 rowHasChanged
函數(shù),在當數(shù)據(jù)源中的數(shù)據(jù)發(fā)生變化時被觸發(fā)褪子。
根組件被創(chuàng)建時骗村,我們往數(shù)據(jù)源中寫入一些數(shù)據(jù)。在 renderRow
函數(shù)中胚股,將每一行數(shù)據(jù)渲染成一個 Text 組件。
運行效果如下: