ListView 实现 带标题的列表:
import React,{Component} from 'react'; import { StyleSheet,ListView,SectionList,View,Text,TouchableOpacity,Image,Alert,} from 'react-native'; 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 style={styles.listViewStyle} dataSource={this.state.dataSource} renderRow={this._renderRow} renderSectionHeader={this._renderSectionHeader}/> </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:{ },iconStyle: { width: 80,height: 80,},itemStyle: { paddingBottom: 10,flexDirection: 'row',alignItems: 'center',sectionHeaderViewStyle: { backgroundColor: '#e8e8e8',height: 25,justifyContent: 'center' },carNameStyle:{ marginLeft:10,})
不论大神还是新手,欢迎加QQ群一起讨论问题学习技术:230274309