FlatList와 SectionList는 모두 데이터 목록을 렌더링하는 데 사용되는 React Native의 컴포넌트입니다.

FlatList는 모든 항목이 동일한 유형인 항목의 목록을 렌더링하는 데 사용됩니다. 성능이 핵심 요소인 긴 데이터 목록에 가장 적합합니다. FlatList는 화면에 표시되는 항목만 렌더링하므로 애플리케이션의 전반적인 성능이 향상됩니다.

SectionList는 섹션으로 나뉜 항목 목록을 렌더링하는 데 사용됩니다. 각 섹션은 머리글과 바닥글을 가질 수 있으며 다양한 유형의 항목을 포함할 수 있습니다. 분류하거나 그룹화해야 하는 복잡한 데이터를 렌더링하는 데 가장 적합합니다. 섹션 목록은 또한 화면에 표시되는 항목만 렌더링하여 성능에 최적화되어 있습니다.

React Native의 FlatList를 랩핑하는 방식으로 SectionList와 같은 컴포넌트를 만들 수 있습니다. FlatList 컴포넌트를 사용하고 각각의 섹션 프롭을 이용하여 데이터를 그룹화하면 됩니다.

import { FlatList } from 'react-native';

const MySectionListOne = ({ sections, renderItem, renderSectionHeader }) => {
  // Group data by section key
  const data = sections.reduce((acc, section) => {
    return [
      ...acc,
      { section: true, title: section.title },
      ...section.data.map(item => ({ ...item, section: false })),
    ];
  }, []);

  // Render item or section header based on section property
  const renderItemOrHeader = ({ item }) => {
    if (item.section) {
      return renderSectionHeader(item);
    }
    return renderItem(item);
  };

  return (
    <FlatList
      data={data}
      renderItem={renderItemOrHeader}
      keyExtractor={(item, index) => `${item.id}-${index}`}
    />
  );
};

export default MySectionListOne;

또는 맵 함수를 사용하여 섹션과 데이터 속성을 가진 객체가 포함된 배열을 반복 할 수 있습니다.
MyFlatListTwo 컴포넌트 자체는 목록 위에 제목을 표시하는 Text 컴포넌트가 있는 FlatList 컴포넌트를 감싸는 간단한 래퍼입니다.
이 접근 방식을 사용하면 SectionList 컴포넌트와 비슷한 방식으로 여러 개의 FlatList 컴포넌트를 렌더링할 수 있습니다.

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

const DATA = [
  {
    title: 'Fruits',
    data: ['Apple', 'Banana', 'Cherry'],
  },
  {
    title: 'Vegetables',
    data: ['Carrot', 'Eggplant', 'Tomato'],
  },
];

const MyFlatList = ({ title, data }) => (
  <>
    <Text>{title}</Text>
    <FlatList
      data={data}
      renderItem={({ item }) => <Text>{item}</Text>}
      keyExtractor={(item) => item}
    />
  </>
);

const MySectionListTwo = () => (
  <View>
    {DATA.map(({ title, data }) => (
      <MyFlatList title={title} data={data} key={title} />
    ))}
  </View>
);

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
http://bit.ly/3Y34pE0

Posted by cipleee