ReactNative 中 ListView实现GridView效果

我们希望能够尽我们所能,来让这个世界变的更简单,如果你想了解我们,请点击这里


在RN中ListVIew拥有ScrollView的所有属性,所以可以吧ListView当成是ScrollView的一种延伸,在RN中虽然不存在父子类,不过我觉的可以把 ListView当成ScrollView的子类来看。
所以改变ListView的排列方式其实就是改变lIstView的主轴的方向。

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView,
    Image,
    TouchableOpacity,
    AlertIOS
} from 'react-native';

var Dimensions = require('Dimensions');
var {width} = Dimensions.get('window');
var {height} = Dimensions.get('window');

var shareData = require('./shareData.json').data;

var GridView = React.createClass({

    getDefaultProps(){
        return{
            // ..ListView.propTypes
        }
    },

    getInitialState(){

        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        return {
            dataSource:ds.cloneWithRows(shareData)
        }
    },


    render(){
        return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
                contentContainerStyle={styles.listStyle}
                showsVerticalScrollIndicator={false}
                showsHorizontalScrollIndicator={false}
            />
        )
    },

//    返回Item试图
    renderRow(rowData,sectionId,rowId,hItemId){
        return(
            <TouchableOpacity
                style={styles.itemViewStyle}
                onPress={() => {AlertIOS.alert(rowId)}}
            >
                <View style={styles.itemViewStyle}>
                    <Image source={{uri:rowData.icon}} style={styles.itemIconStyle}/>
                    <Text style={styles.itemTitleStyle}>{rowData.title}</Text>
                </View>
            </TouchableOpacity>
        )
    }
})

const styles = StyleSheet.create({
    listStyle:{
        flexDirection:'row', //改变ListView的主轴方向
        flexWrap:'wrap', //换行
    },
    itemViewStyle:{
        alignItems:'center', //这里要注意,如果每个Item都在外层套了一个 Touchable的时候,一定要设置Touchable的宽高
        width: width / 3,
        height:100
    },
    itemIconStyle:{
        width:60,
        height:60
    },
    itemTitleStyle:{
        marginTop:8
    }
});

module.exports = GridView;

猜你喜欢

转载自blog.csdn.net/u011068996/article/details/52875780