FlatList 컴포넌트는 데이터 구조가 비슷한 경우사용하기 위해 디자인되었다.

1
2
3
<FlatList
    data={this.state.data}
    renderItem={this._renderItem} />
cs


이 컴포넌트는 props로 data와 renderItem을 반드시 지정해야한다.

data는 FlatList에서 렌더링할 데이터를 의미한다. 데이터는 배열타입으로 배열데이터 항목은 고유의 key 값을 가지고 있어야한다. 

renderItem 함수는 data배열에 속한 데이터를 바탕으로 해당하는 컴포넌트를 리턴하도록 구현한다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import React, { Component } from 'react';
import {StyleSheet, Text, View, FlatList} from "react-native";
 
 
 
class SimpleList extends Component {
 
    constructor(props) {
        super(props);
        this.state = {
            data : [
                {key: "a"},
                {key: "b"},
                {key: "c"},
                {key: "d"},
                {key: "e"},
                {key: "f"},
                {key: "g"},
                {key: "h"},
                {key: "i"},
                {key: "j"},
                {key: "k"},
                {key: "l"},
                {key: "m"},
                {key: "n"},
                {key: "o"},
                {key: "p"},
                {key: "q"},
                {key: "r"}
            ]
        }
    }
 
    _renderItem = ({item}) => {
        return <Text style={styles.row}>
                    {item.key}
                </Text>
    };
 
    render() {
        return (
             <View style={styles.container}>
                <FlatList
                    data={this.state.data}
                    renderItem={this._renderItem}
                    />
             </View>
        );
    }
 
}
 
 
const styles = StyleSheet.create({
    
    container : {
        flex : 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: "#F5FCFF"
    }, row : {
        flex : 1,
        fontSize:24,
        padding: 42,
        borderWidth: 1,
        borderColor: "#DDDDDD"
    }
});
export default SimpleList;

cs

[SimpleListDemo.js]

_renderItem에는 FlatList에 표현할 row항목을 디자인하여 return 하게끔 구성한다. 

뉴욕API 목록 갱신하기 예제 (API 연동전)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import React, { Component } from 'react';
import {StyleSheet, Image, FlatList, View, Text } from 'react-native';
import BookItem from "./BookItem";
 
const mockBooks = [
    {
        rank : 1,
        title : "GATHERING PREY",
        author : "John Sandford",
        book_image : "https://i.postimg.cc/cLdPyZLY/host1.jpg"
    },
    {
        rank : 2,
        title : "MEMORY MAN",
        author : "David Baldacci",
        book_image : "https://i.postimg.cc/3rcwxSvd/host2.jpg"
    }
 
];
 
class BookList extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data: this._addKeysToBooks(mockBooks)};
    };
 
    _renderItem = ({item}) => {
 
        return (
            <BookItem
            coverURL={item.book_image}
            title={item.key}
            author={item.author}
            />
        )
    };
 
    _addKeysToBooks = books => {
        //뉴욕타임스 api 응답을 가져와서 렌더링을 위한 key 속성을 객체에 추가 
        return books.map(book => {
          return Object.assign(book, {key: book.title});
        });
    };
    render() {
      return <FlatList
                data={this.state.data}
                renderItem={this._renderItem}
            />
    }
  }
 
  const styles = StyleSheet.create({
        container : {
            flex : 1,
            paddingTop: 22,
        }
  });
 export default BookList;

cs

[BookList.js]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React, { Component } from "react";
 
import { StyleSheet, Text, View, Image, ListView } from "react-native";
 
const styles = StyleSheet.create({
  bookItem: {
    flexDirection: "row",
    backgroundColor: "#FFFFFF",
    borderBottomColor: "#AAAAAA",
    borderBottomWidth: 2,
    padding: 5,
    height: 175
  },
  cover: {
    //width: "10%", height: "20%" 
       flex: 1
       height: 150
       resizeMode: "contain" 
    },
  info: {
    flex: 3,
    alignItems: "flex-end",
    flexDirection: "column",
    alignSelf: "center",
    padding: 20
  },
  author: { fontSize: 18 },
  title: { fontSize: 18, fontWeight: "bold" }
});
 
class BookItem extends Component {
  render() {
    return (
      <View style={styles.bookItem}>
        <Image style={styles.cover} source={{uri: this.props.coverURL}} />
        <View style={styles.info}>
          <Text style={styles.author}>{this.props.author}</Text>
          <Text style={styles.title}>{this.props.title}</Text>
        </View>
 
        
      </View>
    );
  }
}
 
export default BookItem;
 
cs

[BookItem.js]


1
2
3
4
5
6
7
8
9
10
import React, {Component} from 'react';
import BookList from './bookstore/BookList';
 
export default class App extends Component {
  render() {
    return (
        <BookList/>
      );
  }
}

cs

[App.js]


실제 데이터 연결예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const API_KEY = "73b19491b83909c7e07016f4bb4644f9:2:60667290";
const LIST_NAME = "hardcover-fiction";
const API_STEM = "https://api.nytimes.com/svc/books/v3/lists";
 
 
function fetchBooks(list_name = LIST_NAME) {
    let url = `${API_STEM}/${LIST_NAME}?response-format=json&api-key=${API_KEY}`;
    return fetch(url)
        .then(response => response.json())
        .then(data => {
            return data.results.books;
        })
        .catch(error => {
            console.log(error);
        });
}
export default { fetchBooks: fetchBooks};
 
 
cs

[NYT.js]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import React, { Component } from 'react';
import {StyleSheet, Image, FlatList, View, Text } from 'react-native';
import BookItem from "./BookItem";
import NYT from "./NYT";
 
class BookList extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data: []};
    };
 
 
    componentDidMount() {
        this._refreshData();
    }
 
    _renderItem = ({item}) => {
 
        return (
            <BookItem
            coverURL={item.book_image}
            title={item.key}
            author={item.author}
            />
        )
    };
 
    _addKeysToBooks = books => {
        //뉴욕타임스 api 응답을 가져와서 렌더링을 위한 key 속성을 객체에 추가 
        return books.map(book => {
          return Object.assign(book, {key: book.title});
        });
    };
 
    _refreshData = () => {
        NYT.fetchBooks().then(books => {
            this.setState({data:this._addKeysToBooks(books)});
        });
    }
 
    render() {
      return <FlatList
                data={this.state.data}
                renderItem={this._renderItem}
            />
    }
  }
 
  
 
  export default BookList;
cs

[BookList.js]

NYT 모듈을 import에 추가한다. _refreshData() 메서드를 추가하고 NYT.fetchBooks 메서드를 이용하여 데이터를 가져오게끔 코드를 추가한다. 37~39라인 




FlastList관련참고

예제소스 참고 : 빠른 모바일 앱 개발을 위한 React Native 2/E


블로그 이미지

클라인STR

,