React Native之九宫格布局

来源:互联网 发布:java 高德地图api 编辑:程序博客网 时间:2024/05/16 18:31

九宫格的布局,其实大家都耳熟能详了,那么如何用react native来开发九宫格布局呢?

首先,贴上UI需求图:




对于以上的布局,虽然目前图片还是很少,还是希望大家可以用最优雅的方式开发代码,简洁好看,复用性也高。

开发的思想:

将图片的所有信息(包括URL地址,图片文字,是否是大图还是小图等等)都整合在一个对象里面,可以在当前模块中数据传递,也可以支持从上级传递数据。

以下就是本次九宫格开发的核心代码块:

generateDetailItems(){        var arr=[];        var badge = this.state.imageList;        if(badge){            for (var i = 0;i<badge.length;i++){                if(badge[i].bigOr==0){                    arr.push(                        <View style={styles.viewStyle}>                            <Image source={badge[i].imgUrl} style={styles.faceWidth} resizeMode={Image.resizeMode.contain} />                            <Text style={styles.textStyle}>{badge[i].textDesc}</Text>                        </View>                    );                }else{                    arr.push(                        <View style={styles.outerViewStyle}>                            <View style={styles.viewStyle}>                                <Image source={badge[badge.length-1].imgUrl} style={styles.bigImage} resizeMode={Image.resizeMode.contain} />                                <Text style={styles.textStyle}>{badge[badge.length-1].textDesc}</Text>                            </View>                        </View>                    );                }            }            return arr;        }}


初始化imageList如下:

constructor(props) {        super(props);        this.props = props;        this.state = {            imageList:[                {imgUrl: require('./image/far.png'), textDesc:'太远',bigOr:0},                {imgUrl: require('./image/close.png'), textDesc:'太近',bigOr:0},                {imgUrl: require('./image/dark.png'), textDesc:'太暗',bigOr:0},                {imgUrl: require('./image/badBg.png'), textDesc:'背景复杂凌乱',bigOr:0},                {imgUrl: require('./image/dim.png'), textDesc:'对焦模糊',bigOr:0},                {imgUrl: require('./image/reflect.png'), textDesc:'反光',bigOr:0},                {imgUrl: require('./image/right.png'), textDesc:'正确姿势',bigOr:1},            ] || this.props.imageList,        }}


具体详情和使用,请去我的Github下载源码:

https://github.com/spicyboiledfish/GridView



原创粉丝点击