Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้งาน VirtualizedList ใน React Native


VirtualizedList เหมาะสำหรับรายการขนาดใหญ่มาก ช่วยประสิทธิภาพและหน่วยความดีขึ้น ข้อมูลจะแสดงเมื่อผู้ใช้เลื่อน (scroll)

คอมโพเนนต์พื้นฐาน

<VirtualizedList
  data={DATA}
  initialNumToRender={4}
  renderItem={renderItem}
  keyExtractor={keyExtractor}
  getItemCount={getItemCount}
  getItem={getItem}
/>

คุณสมบัติสำคัญ

Props คำอธิบาย
renderItem แสดงรายการจากข้อมูลภายใน VirtualizedList
data ข้อมูลที่จะแสดง
getItem ฟังก์ชันดึงรายการเดี่ยวจากข้อมูล
getItemCount ดึงจำนวนรายการข้อมูล
initialNumToRender จำนวนรายการที่ render เริ่มต้น
keyExtractor Unique key สำหรับแต่ละรายการใน index ที่กำหนด

ตัวอย่าง: แสดงข้อมูลด้วย VirtualizedList

import { SafeAreaView, View, VirtualizedList, StyleSheet, Text } from 'react-native';
<SafeAreaView>
  <VirtualizedList
    data={DATA}
    initialNumToRender={4}
    renderItem={({ item }) => <Item title={item.title} />}
    keyExtractor={item => item.id}
    getItemCount={getItemCount}
    getItem={getItem}
  />
</SafeAreaView>

รายการเริ่มต้นที่ render คือ 4 รายการ renderItem ใช้ custom Item component:

const Item = ({ title }) => {
  return (
    
      {title}
    
  );
};

keyExtractor กำหนด unique key:

keyExtractor={item => item.id}

getItemCount ดึงจำนวนรายการทั้งหมด:

const getItemCount = (data) => {
  return 100;
};

getItem ดึงข้อมูลรายการ:

const getItem = (data, index) => {
  return {
    id: index,
    title: 'test'
  };
};

โค้ดเต็มรูปแบบ

import React from 'react';
import { SafeAreaView, View, VirtualizedList, StyleSheet, Text } from 'react-native';

const DATA = [];

const getItem = (data, index) => {
  return {
    id: index,
    title: 'test'
  };
};

const getItemCount = (data) => {
  return 100;
};

const Item = ({ title }) => {
  return (
    
      {title}
    
  );
};

const VirtualizedListExample = () => {
  return (
    
       }
        keyExtractor={item => item.id}
        getItemCount={getItemCount}
        getItem={getItem}
      />
    
  );
};

const styles = StyleSheet.create({
  item: {
    backgroundColor: '#ccc',
    height: 100,
    justifyContent: 'center',
    marginVertical: 8,
    marginHorizontal: 16,
    padding: 20,
  },
  title: {
    fontSize: 32,
  },
});

export default VirtualizedListExample;

ผลลัพธ์

การใช้งาน VirtualizedList ใน React Native

เมื่อไหร่ควรใช้ VirtualizedList

  • รายการขนาดใหญ่ (พันๆ รายการขึ้นไป)
  • ข้อมูลโหลดแบบ lazy (ไม่ได้มีข้อมูลทั้งหมดตั้งแต่แรก)
  • ต้องการควบคุมการ render แบบ manual
  • FlatList และ SectionList ใช้ VirtualizedList เป็น base อยู่แล้ว ส่วนใหญ่ควรใช้ FlatList/SectionList แทน