[TIL] React Native-FlatList, SectionList

link717ยท2020๋…„ 11์›” 29์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
22/53
post-thumbnail

๐Ÿ”Š FlatList component

React์—์„œ ์‚ฌ์šฉํ•œ JavaScript์˜ map method์™€ ๋™์ผํ•œ ๊ธฐ๋Šฅ์„ ํ•˜๋Š” component์ด๋‹ค. map method์™€ ๋‹ฌ๋ฆฌ ์œ ์šฉํ•œ props๋“ค์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์žฅ์ ์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— React Native์—์„œ๋Š” map ๋Œ€์‹  FlatList component๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

// 1. map method
{data.map(el => {
  return (
    <OneItem
      key={el.id}
      content={el.content}
    />
   )
})}

 // 2. FlatList component
 // item์ด๋ผ๋Š” argument ์ด๋ฆ„์€ ๋‹ค๋ฅธ ๊ฒƒ์œผ๋กœ ๋ฐ”๊พธ๋ฉด ์•ˆ๋œ๋‹ค.
 // keyExtractor(key)๋Š” string ํ˜•ํƒœ์—ฌ์•ผ ํ•œ๋‹ค.
 
<FlatList
  data={data}
  renderItem={({item}) => {
    <OneItem
      content={item.content}
    />
  }}
  keyExtractor={{item=>String(item.id)}
/>

ScrollView vs FlatList

  • ScrollView: ํ™”๋ฉด์— ๋ณด์—ฌ์ง€๋Š” ๊ฒƒ๊ณผ ์ƒ๊ด€์—†์ด ScrollView๊ฐ€ ๊ฐ์‹ธ๊ณ  ์žˆ๋Š” ๋ชจ๋“  Component๋ฅผ render ํ•œ๋‹ค.
  • FlatList: ํ™”๋ฉด์— ๋ณด์—ฌ์ง€๋Š” ๋ถ€๋ถ„๋งŒ renderํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฉ”๋ชจ๋ฆฌ ์ตœ์ ํ™”๋ฅผ ์œ„ํ•ด์„œ ์‚ฌ์šฉํ•œ๋‹ค.
    (Pagination ๊ตฌํ˜„ํ•  ๋•Œ ํ•„์ˆ˜๋กœ ์‚ฌ์šฉ)

๐Ÿ”Š SectionList component

React์—์„œ ์‚ฌ์šฉํ•œ JavaScript์˜ map method๋ฅผ ๋ฐ˜๋ณตํ•˜์—ฌ ์‚ฌ์šฉํ•œ ๋“ฏํ•œ ํšจ๊ณผ๋ฅผ ์ฃผ๋Š” component์ด๋‹ค. ํŽ˜์ด์ง€ ๊ตฌ์„ฑ์‹œ item ๋ชฉ๋ก๋“ค์˜ ๋ถ„๋ฆฌ๊ฐ€ ํ•„์š”ํ•œ ๊ฒฝ์šฐ์— (header - listitem) * n๊ฐœ์˜ ํšจ๊ณผ๋ฅผ ์ค„ ์ˆ˜ ์žˆ๋‹ค.

// section title์— ํ•ด๋‹นํ•˜๋Š” ๋ถ€๋ถ„์€ renderSectionHeader์˜ props์— ์ „๋‹ฌํ•œ๋‹ค.

const DATA = [
  {
    title: "Main",
    item: ["Pizza", "Hamburger", "Risotto"]
  },
  {
    title: "Drinks",
    item: ["Water", "Coke", "Beer"]
  }  
] 

    <SectionList
      sections={DATA}
      keyExtractor={(item, index) => item + index}
      renderItem={({ item }) => <Item title={item} />}
      renderSectionHeader={({ section: { title } }) => (
        <Text style={styles.header}>{title}</Text>
      )}
    />
profile
Turtle Never stop

0๊ฐœ์˜ ๋Œ“๊ธ€