/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView,
Image,
TouchableOpacity,
} from 'react-native';
var Car = require('./Car.json');
export default class HeCan extends Component {
constructor(props){
super(props);
var getSectionHeaderData =(dataBlob, sectionID)=>{
return dataBlob[sectionID];
};
var getRowData = (dataBlob, sectionID, rowID) =>{
//這個(gè)是自己定義的規(guī)則
return dataBlob[sectionID+'&'+rowID];
};
this.state ={
dataSource:new ListView.DataSource({
getSectionHeaderData:getSectionHeaderData,
getRowData:getRowData,
rowHasChanged:(r1,r2)=>r1!==r2,
sectionHeaderHasChanged:(s1,s2)=>s1!==s2,
})
}
}
//------
render() {
return (
<View style={styles.container}>
{/*頭部Nav*/}
<View style={styles.NavViewStyle}>
<Text style={{color:'white',fontSize:25}}>這是汽車品牌展示</Text>
</View>
{/*ListView*/}
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
renderSectionHeader={this.renderSectionHeader}
/>
</View>
);
}
//返回每一組頭部的內(nèi)容
renderSectionHeader(sectionData,sectionID){
return(
<View style={styles.sectionHeaderStyle}>
<Text style={{marginLeft:5,color:'red'}}>{sectionData}</Text>
</View>
)
}
//返回每一行Cell
renderRow(rowData){
return(
<TouchableOpacity activeOpacity={0.5}>
<View style={styles.rowStyle}>
<Image source={{uri:rowData.icon}} style={styles.rowImageStyle}/>
<Text style={{marginLeft:5}}>{rowData.name}</Text>
</View>
</TouchableOpacity>
)
}
//------
//這一步需要請(qǐng)求數(shù)據(jù)
componentDidMount()
{
this.loadJson();
}
loadJson(){
//拿到Json
var jsonData = Car.data;
//定義數(shù)據(jù)源需要的變量
var dataBlob = {},
sectionIDs = [],
rowIDs = [],//二維數(shù)組!!
cars = [];
//遍歷
for(var i=0;i<jsonData.length;i++){
//1.組ID拿到
sectionIDs.push(i);
//2.dataBlob
dataBlob[i] = jsonData[i].title;
//3.取出這一組的所有的車
cars = jsonData[i].cars;
rowIDs[i] = [];
for (var j=0;j<cars.length;j++){
//i組的j行 那么這一行的ID 就是 j
rowIDs[i].push(j);
//每一行的內(nèi)容放到dataBlob里面了!!
dataBlob[i+'&'+j] = cars[j];
}
}
//更新狀態(tài)機(jī)!!
this.setState({
dataSource:this.state.dataSource.cloneWithRowsAndSections(dataBlob,sectionIDs,rowIDs)
})
}
}
const styles = StyleSheet.create({
container:{
flex:1,
},
NavViewStyle:{
height:64,
backgroundColor:'orange',
justifyContent:'center',
alignItems:'center',
},
rowStyle: {
padding:10,
flexDirection:'row',
alignItems:'center',
//cell分割線
borderBottomColor:'#e8e8e8',
borderBottomWidth:0.5
},
rowImageStyle:{
width:70,
height:70
},
sectionHeaderStyle:{
backgroundColor:'#e8e8e8',
height:25,
justifyContent:'center',
}
});
Car.json數(shù)據(jù)的格式如下
{
"data": [
{
"cars": [
{
"icon": "m_180_100.png",
"name": "AC Schnitzer"
},
{
"icon": "m_92_100.png",
"name": "阿爾法·羅密歐"
},
{
"icon": "m_9_100.png",
"name": "奧迪"
},
{
"icon": "m_97_100.png",
"name": "阿斯頓·馬丁"
}
],
"title": "A"
},
{
"cars": [
{
"icon": "m_172_100.png",
"name": "巴博斯"
},
{
"icon": "m_157_100.png",
"name": "寶駿"
},