美文网首页
react native 网格列表

react native 网格列表

作者: _悟_空 | 来源:发表于2019-10-09 13:27 被阅读0次

先看效果图👇

gridList.gif

理解

1.react native没有网格列表的控件,所以我们采用的是最外层为ScrollView
2.每两个横向的子条目共用一个父View
3.list数据需要提前处理为二维数组。因为每个条目有两个子view。

看下图可知晓👇:View结构


explain.jpg

数据方面也同样需要配合VIew条目去做变动。格式如下👇;
变动前:

[
    '海贼王',
    '火影忍者',
    '斗破苍穹',
    '疾风传',
    '路飞',
    '鸣人',
    '二柱子',
    '索罗',
    '乌索普',
    '娜美',
    '罗兵',
    '乔巴',
    '萧炎',
    '萧薰儿',
    '诛仙',
    '张小凡',
    '林惊羽',
    '万剑一',
    '碧瑶',
    '陆雪琪',
    '小白',
  ]

变动后👇:

[
["海贼王", "火影忍者"], 
["斗破苍穹", "疾风传"], 
["路飞", "鸣人"], 
["二柱子", "索罗"], 
["乌索普", "娜美"], 
["罗兵", "乔巴"], 
["萧炎", "萧薰儿"], 
["诛仙", "张小凡"], 
["林惊羽", "万剑一"], 
["碧瑶", "陆雪琪"], 
["小白", undefined]
]

注意点

每个父级条目实际上是包括了两个子条目。

核心代码如下:

//list转二维数组,这个很好理解。
export const getArray = (list) =>{
    let arry=[];

    for(var i=0;i<list.length;i+=2){
      let fu = [];
      fu.push(list[i]);
      if((i+1)<=list.length){
        fu.push(list[i+1]);
      }
      arry.push(fu);
    }
    return arry;
}
//条目展示的代码
itemView = () => {
  let list = [
    '海贼王',
    '火影忍者',
    '斗破苍穹',
    '疾风传',
    '路飞',
    '鸣人',
    '二柱子',
    '索罗',
    '乌索普',
    '娜美',
    '罗兵',
    '乔巴',
    '萧炎',
    '萧薰儿',
    '诛仙',
    '张小凡',
    '林惊羽',
    '万剑一',
    '碧瑶',
    '陆雪琪',
    '小白',
  ];

  console.log(getArray(list));

  return getArray(list).map((item, index) => (
    <View
      style={{height: 50, flexDirection: 'row'}}
      key={index + Math.random()}>
      {item[0] ? (
        <View style={styles.item}>
          <Text>{item[0]}</Text>
        </View>
      ) : null}
      {item[1] ? (
        <View style={styles.item2}>
          <Text>{item[1]}</Text>
        </View>
      ) : (
        <View style={{flex: 1, marginLeft: 5, marginRight: 5}}></View>
      )}
    </View>
  ));
};
.....
.....
const styles = StyleSheet.create({
  item: {
    height: 40,
    backgroundColor: '#F4F4F4',
    flex: 1,
    marginLeft: 5,
    marginRight: 5,
    alignItems: 'center',
    justifyContent: 'center',
  },
  item2: {
    height: 40,
    backgroundColor: '#3DC6AA',
    flex: 1,
    marginLeft: 5,
    marginRight: 5,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

项目地址

相关文章

网友评论

      本文标题:react native 网格列表

      本文链接:https://www.haomeiwen.com/subject/rqgbpctx.html