[RN] React Native 下列表 FlatList 和 SectionList

1、FlatList

FlatList组件用于显示一个垂直的滚动列表,其中的元素之间结构近似而仅数据不同。

FlatList更适于长列表数据,且元素个数可以增删。和ScrollView不同的是,FlatList并不立即渲染所有元素,而是优先渲染屏幕上可见的元素。

FlatList组件必须的两个属性是datarenderItemdata是列表的数据源,而renderItem则从数据源中逐个解析数据,然后返回一个设定好格式的组件来渲染。

示例代码:

import React, {Component} from "react";
import {FlatList, StyleSheet, Text, View} from "react-native";

var data = [
    {key: "黑猫警长2", val: "美国"},
    {key: "我是特种兵", val: "中国"},
    {key: "变形金刚2", val: "美国"},
    {key: "流浪地球", val: "中国"},
];

export default class HelloWorld extends Component {
    render() {
        return (
            <View style={styles.container}>
                <FlatList
                    data={data}
                    renderItem={
                        ({item}) =>
                            <Text style={styles.item}>{item.key} [{item.val}]</Text>
                    }
                />
            </View>
        )
    }
}

const styles = StyleSheet.create(
    {
        container: {
            flex: 1,
            paddingTop: 22,
            backgroundColor: "#cccccc",
        },
        item: {
            padding: 10,
            fontSize: 18,
            height: 44,
        }
    }
);

 

效果如下:

 

2、SectionList

适用于要渲染的是一组需要分组的数据,也许还带有分组标签的

示例代码:

import React, {Component} from "react";
import {SectionList, StyleSheet, Text, View} from "react-native";

var data = [
    {title2: '中国', data: ['万里长城',"故宫","颐和园"]},
    {title2: '美国', data: ['白宫',"拉斯维加斯"]},
];

export default class HelloWorld extends Component {
    render() {
        return (
            <View style={styles.container}>
                <SectionList sections={data}
                             renderItem={
                                 ({item}) =>
                                     <Text style={styles.item}>{item}</Text>
                             }
                             renderSectionHeader={({section}) => <Text
                                 style={styles.sectionHeader}>{section.title2}</Text>}
                             keyExtractor={(item, index) => index}
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 22
    },
    sectionHeader: {
        paddingTop: 2,
        paddingLeft: 10,
        paddingRight: 10,
        paddingBottom: 2,
        fontSize: 18,
        fontWeight: 'bold',
        backgroundColor: 'rgba(247,247,247,1.0)',
    },
    item: {
        padding: 10,
        fontSize: 16,
        height: 44,
    },
})

 

效果如下:

 

本博客地址: wukong1688

本文原文地址:https://www.cnblogs.com/wukong1688/p/10804252.html

转载请著名出处!谢谢~~

 

posted @ 2019-05-03 08:05  wukong1688  阅读(1012)  评论(0编辑  收藏  举报