React Native
列表視圖 ListView
ListView 是一個特殊的 ScrollView,用來展示一個縱向排列結構相似的內容。
ListView 可以高效地處理大量數據,它不像 ScrollView 將所有包含其中的組件都渲染出來,它只會渲染當前會顯示在屏幕上的內容。
ListView 組件創建時需要設置兩個屬性:
-
dataSource
:列表視圖顯示內容的數據源。 -
renderRow
:渲染每行內容的方法。
下面展示一個實例:
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);
這個例子中,先創建一個 ListView.DataSource
,在創建時,需要提供一個 rowHasChanged
函數,在當數據源中的數據發生變化時被觸發。
根組件被創建時,我們往數據源中寫入一些數據。在 renderRow
函數中,將每一行數據渲染成一個 Text 組件。
運行效果如下:
ListView