ListView 实现多列列表
import React, {Component} from 'react';
import {
StyleSheet,
ListView,
SectionList, View, Text, TouchableOpacity, Image, Alert,
} from 'react-native';
var {width, height} = require('Dimensions').get('window');
var cols = 3;
var cellWH = width/4;
var hMargin = (width - cols * cellWH) / (cols + 1);
var vMargin = 25;
import carInfos from '../data/carBrandData.json'
/**
* 1. 于state 中 初始化dataSource
* 2. 在componentDidMount 中请求数据 并更新state 中的 dataSource
* 3. render() 返回 renderRow&Section、 renderHeader
*/
export default class CarBrandList extends Component {
constructor(props) {
super(props);
let _getSectionData = (dataBlob, sectionID) => {
return dataBlob[sectionID];
};
let _getRowData = (dataBlob, sectionID, rowID) => {
return dataBlob[sectionID + ':' + rowID];
};
this.state = {
//1.初始化dataSource
dataSource: new ListView.DataSource({
getSectionData: _getSectionData,
getRowData: _getRowData,
rowHasChanged: (r1, r2) => {
r1 !== r2
},
sectionHeaderHasChanged: (s1, s2) => {
s1 !== s2
},
}),
}
}
componentDidMount() {
//2.请求数据 更新数据
this._requestCarInfo();
}
_requestCarInfo() {
let jsonData = carInfos.data;
let dataBlob = {},
sectionIDs = [],
rowIDs = [],
cars = [];
// 处理数据成可用格式
for (let i = 0; i < jsonData.length; i++) {
//1.把组号放入sectionIDs中
sectionIDs.push(i);
//2.把组中的内容放入dataBlob
dataBlob[i] = jsonData[i].title;
//3.取出组中的数据//TODO:这个地方 为什么不是cars[i]
cars = jsonData[i].cars;
rowIDs[i] = [];
//遍历所有的车数组
for (let j in cars) {
//把行号放入rowIDs
rowIDs[i].push(j);
//把每一行的内容放入dataBlob 对象中
dataBlob[i + ':' + j] = cars[j];
}
}
console.log(dataBlob);
console.log(sectionIDs);
console.log(rowIDs);
// 数据处理完成,更新状态机
this.setState({
dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs),
})
}
render() {
return (
<View>
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow}
renderSectionHeader={this._renderSectionHeader}
contentContainerStyle={styles.listViewStyle}/>
</View>
);
}
_renderRow(rowData) {
return (
<TouchableOpacity activeOpacity={0.5} onPress={() => Alert.alert(
rowData.name,
)}>
<View style={styles.itemStyle}>
<Image
source={{uri: rowData.icon}}
style={styles.iconStyle}/>
<Text style={styles.carNameStyle}>{rowData.name}</Text>
</View>
</TouchableOpacity>
);
}
_renderSectionHeader(sectionData, sectionID) {
return (
<View style={styles.sectionHeaderViewStyle}>
<Text style={{marginLeft: 5, color: 'red'}}>{sectionData}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
listViewStyle: {
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'center',
},
iconStyle: {
width: cellWH,
height: cellWH,
},
itemStyle: {
width: cellWH,
height: cellWH+20,
marginLeft: hMargin,
marginTop: vMargin,
alignItems: 'center'
// paddingBottom: 10,
// flexDirection: 'row',
// alignItems: 'center',
},
sectionHeaderViewStyle: {
width:width,
backgroundColor: '#e8e8e8',
height: 25,
justifyContent: 'center'
},
carNameStyle:{
marginLeft:10,
},
})
使用的是ListView的样式属性 来实现多行的功能。