React Native简单的九宫格布局

/ 0评 / 0

首先我们需要准备数据,准备六张图(名字要与资源文件中的一致),放入xcode工程中的Images.xcassets中,然后准备json文件

{
  "data": [
    {
      "icon" : "danjianbao",
      "title" : "单肩包"
    },
    {
      "icon" : "liantiaobao",
      "title" : "链条包"
    },
    {
      "icon" : "qianbao",
      "title" : "钱包"
    },
    {
      "icon" : "shoutibao",
      "title" : "手提包"
    },
    {
      "icon" : "shuangjianbao",
      "title" : "双肩包"
    },
    {
      "icon" : "xiekuabao",
      "title" : "斜挎包"
    }
  ]
}

加载资源文件并声明全局变量

//加载json文件数据
var BageDate = require('./ImageData.json');

//定义一些全局变量
var {width} = Dimensions.get('window');
var {height} = Dimensions.get('window');

var cols = 3;
var boxW = 100;

var wMargin = (width - cols * boxW) / (cols + 1);
var hMargin = 25;

定义组件

class MyProject2 extends Component {
    render() {
        return (
            
                {/*获取6个包*/}
                {this.renderAllImage()}
            
        );
    }
    /*返回6个包*/
    renderAllImage() {
        //定义数组装所有的子组件
        var allBadge = [];
        //遍历JSON数据
        for (var i=0;i
                    
                    
                        {badge.title}
                    
                
            );
        }
        //返回数组
        return allBadge;
    }
}

设置样式

const styles2 = StyleSheet.create({
    container: {
        //flex: 1, 要换行就要去掉
        backgroundColor: '#F5FCFF',
        flexDirection:'row',
        flexWrap:'wrap',
    },
    outViewStyle:{
        backgroundColor:'gray',
        alignItems:'center',
        width:boxW,
        height:boxW,
        marginLeft:wMargin,
        marginTop:hMargin,
    },
    textImageStyle:{
        width:80,
        height:80,
    },
    textTitleStyle:{

    }
});

效果图

评论已关闭。