代码如下;
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
} from 'react-native';
//导入json数据
var badgeData = require('./BadgeData.json');
var Dimensions=require('Dimensions');
var {width}=Dimensions.get('window');
//定义一些全局变量
var cols=3;
var boxW=100;
var vMargin=(width-cols*100)/(cols+1); // 边距数目 设置左右边距
var hMargin=25; //上下边距
export default class ImageComponent extends Component {
render() {
return (
<View style={styles.container}>
{/* 返回6张图片的json数据 this表示当前的组件*/}
{this.renderAllBadge()}
</View>
);
}
//返回所有的包
renderAllBadge() {
//定义一个数组用来装所有的图片数组
var allBadge = [];
var dataArr = badgeData.data;
//for循环
for (var i = 0; i < dataArr.length; i++) {
//得到单个json对象
var badge = dataArr[i];
//添加到数组箱子里面
allBadge.push(
<View style={styles.outViewStyle}>
<Image key={i} source={{uri:badge.icon}} style={styles.imageStyle}>
</Image>
<Text style={styles.textContentStyle}>
{badge.title}
</Text>
</View>
);
}
return allBadge;
}
}
//style样式设置
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
//确定主轴的方向
flexDirection:'row',
//换行显示
flexWrap:'wrap',
},
//设置外部的style
outViewStyle:{
backgroundColor:'white',
width:boxW,
height:boxW,
marginLeft:vMargin, //设置左边距
marginTop:hMargin, //设置上边距
},
//设置图片样式
imageStyle:{
width:80,
height:80,
},
textContentStyle:{
textAlign:'center',
}
});
//注册组件
AppRegistry.registerComponent('RnFirstApp', () => RnFirstApp);
运行效果如下:
BadgeData.json文件json数据格式如下:
{
"data":[
{
"icon" :
"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3935885658,3389722307&fm=27&gp=0.jpg",
"title" :
"单肩包"
},
{
"icon" :
"https://ss0.bdstatic.com/6ONWsjip0QIZ8tyhnq/it/u=4035832409,561546226&fm=77&src=1009",
"title" :
"链条包"
},
{
"icon" :
"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=66544896,1609626762&fm=27&gp=0.jpg",
"title" :
"钱包"
},
{
"icon" :
"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1300406055,3322031203&fm=27&gp=0.jpg",
"title" :
"手提包"
},
{
"icon" :
"https://ss3.baidu.com/-rVXeDTa2gU2pMbgoY3K/it/u=3589336874,4128426642&fm=202&gp=0.jpg&w_h=121_75&cs=3589336874,4128426642&ow_h=121_75&src=1010&mola=new&crop=v1",
"title" :
"双肩包"
},
{
"icon" :
"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1603855652,2015126712&fm=27&gp=0.jpg",
"title" :
"斜挎包"
}
]
}