Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Component FlatList trong React Native là gì và cách sử dụng


FlatList là một container dùng để hiển thị danh sách các mục (list items). Nó hỗ trợ header/footer, nhiều cột, cuộn dọc/ngang, lazy loading (tải lười) và nhiều tính năng khác.

Các tính năng quan trọng của FlatList:

  • Hỗ trợ cuộn tải (scroll loading)
  • Điều chỉnh cuộn bằng ScrolltoIndex
  • Hỗ trợ header và footer
  • Hỗ trợ nhiều cột
  • Cross-platform (iOS, Android)
  • Callback viewability có thể cấu hình

Cấu trúc cơ bản của FlatList:

<FlatList data={DataContainer} renderItem={yourRenderItem} keyExtractor={item => item.id} />

FlatList được triển khai từ component VirtualizedList, chỉ render số lượng mục vừa đủ hiển thị trong viewport màn hình. Dữ liệu còn lại được render khi người dùng cuộn. Các props cơ bản data và renderItem dùng để tạo FlatList.

Để sử dụng FlatList, import từ react-native:

import { FlatList } from "react-native";

Các props quan trọng của FlatList:

PropsMô tả
dataMảng chứa dữ liệu hiển thị.
renderItemrenderItem({ item, index, separators })
  • item – Mục dữ liệu hiển thị.
  • index – Chỉ số mục.
  • separators – Hàm render phân cách: highlight(), unhighlight(), updateProps().
ListEmptyComponentComponent/hàm/element render khi danh sách rỗng.
ListFooterComponentComponent render ở cuối danh sách.
ListFooterComponentStyleStyle cho footer.
ListHeaderComponentComponent render ở đầu danh sách.
ListHeaderComponentStyleStyle cho header.
horizontalNếu true thì render ngang.
keyExtractorTrích khóa duy nhất cho index: (item, index) => string. Dùng cho cache và theo dõi sắp xếp lại.

Ví dụ 1: Hiển thị dọc (Vertical)

Import các component cần thiết:

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

Dữ liệu lưu trong this.state.data:

this.state = {
    data: [
        { name: "Javascript Frameworks", isTitle: true },
        { name: "Angular", isTitle: false },
        { name: "ReactJS", isTitle: false },
        { name: "VueJS", isTitle: false },
        { name: "ReactNative", isTitle: false },
        { name: "PHP Frameworks", isTitle: true },
        { name: "Laravel", isTitle: false },
        { name: "CodeIgniter", isTitle: false },
        { name: "CakePHP", isTitle: false },
        { name: "Symfony", isTitle: false }
    ],
    stickyHeaderIndices: []
};

Hàm renderItem

Hàm nhận item và hiển thị trong Text, in đậm và đỏ nếu isTitle true:

renderItem = ({ item }) => {
    return (
        
            
                {item.name}
            
        
    );
};

Triển khai FlatList


     item.name}
    />

Gán this.state.data cho data, this.renderItem cho renderItem. keyExtractor dùng item.name làm khóa duy nhất.

Mã hoàn chỉnh:

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

export default class App extends React.Component {
    constructor() {
        super();
        this.state = {
            data: [
                { name: "Javascript Frameworks", isTitle: true },
                { name: "Angular", isTitle: false },
                { name: "ReactJS", isTitle: false },
                { name: "VueJS", isTitle: false },
                { name: "ReactNative", isTitle: false },
                { name: "PHP Frameworks", isTitle: true },
                { name: "Laravel", isTitle: false },
                { name: "CodeIgniter", isTitle: false },
                { name: "CakePHP", isTitle: false },
                { name: "Symfony", isTitle: false }
            ],
            stickyHeaderIndices: []
        };
    }
    renderItem = ({ item }) => {
        return (
            
                
                    {item.name}
                
            
        );
    };
    render() {
        return (
            
                 item.name}
                    stickyHeaderIndices={this.state.stickyHeaderIndices}
                />
            
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: StatusBar.currentHeight || 0,
    },
    item: {
        margin: 10,
        padding: 20,
        marginVertical: 8,
        marginHorizontal: 16,
    }
});

Kết quả

Component FlatList trong React Native là gì và cách sử dụng

Ví dụ 2: Hiển thị ngang (Horizontal)

Thêm props horizontal={true}:

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

export default class App extends React.Component {
    constructor() {
        super();
        this.state = {
            data: [
                { name: "Javascript Frameworks", isTitle: true },
                { name: "Angular", isTitle: false },
                { name: "ReactJS", isTitle: false },
                { name: "VueJS", isTitle: false },
                { name: "ReactNative", isTitle: false },
                { name: "PHP Frameworks", isTitle: true },
                { name: "Laravel", isTitle: false },
                { name: "CodeIgniter", isTitle: false },
                { name: "CakePHP", isTitle: false },
                { name: "Symfony", isTitle: false }
            ],
            stickyHeaderIndices: []
        };
    }
    renderItem = ({ item }) => {
        return (
            
                
                    {item.name}
                
            
        );
    };
    render() {
        return (
            
                 item.name}
                    stickyHeaderIndices={this.state.stickyHeaderIndices}
                />
            
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: 100,
    },
    item: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 30,
        margin: 2,
        borderColor: '#2a4944',
        borderWidth: 1,
        height: 100,
        backgroundColor: '#d2f7f1'
    }
});

Kết quả

Component FlatList trong React Native là gì và cách sử dụng