<ListView>在React Native中是個非常重要的組件,創立最簡單的API"ListView.DataSource",同時給該對像傳入一個簡單的數據集合,並且使用數據源"data source"實例化一個ListView組件,定義一個renderRow回調方法,該renderRow方法會返回一個可顯示的組件,並以列表的方式呈現每一個item
首先介紹ListView為這次標籤,如下所示,
主程式部份,使用props呼叫對應的父類別建構元,接下來創建ListView.DataSource之方法,利用 this.state = {dataSource: ds.cloneWithRows([要顯示的資料]),};,將要顯示的資料填在裏頭
將this.state.dataSource數據存至dataSource,用renderRow取出數據,並用Text顯示
接下來是Style程式,
接下來修改在[筆記]安裝React-Native與創造第一個專案,所創造的專案來演示此功能,
import {
AppRegistry,
StyleSheet,
ListView,
Text,
View
} from 'react-native';
export default class AwesomeProject extends Component {
constructor(props) {
/*
呼叫對應的父類別建構元,props
*/
super(props);
/*
創建ListView.DataSource之方法
*/
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
/*
設置要顯示的文字項目
*/
this.state = {
dataSource: ds.cloneWithRows([
'row 1',
'row 2',
'row 3',
'row 4',
'row 5',
'row 6',
'row 7',
'row 8',
'row 9',
'row 10',
'row 11',
'row 12'
]),
};
}
render() {
return (
<View style={styles.container}>
<ListView
/*
將this.state.dataSource數據存至dataSource
*/
dataSource={this.state.dataSource}
/*
用renderRow取出數據,並用Text顯示
*/
renderRow={(rowData) => <Text style={styles.fontSize24}>{rowData}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
/*
父類別flex:1充滿整個空間
padding: 10 在畫面左方預留10之大小的空白
justifyContent: 'flex-start' 佈局對齊方式:從開始端進行對齊
alignItems: 'flex-start' 項目對齊方式:從開始端進行對齊
*/
container: {
flex: 1,
padding: 10,
justifyContent: 'flex-start',
alignItems: 'flex-start'
},
/*
字形大小 24
*/
fontSize24: {
fontSize: 24
}
});
在Node.js command prompt執行"react-native run-android",即可安裝在模擬器或手機上演示,