Skip to Content
MobileReact Native02-Core Component

1. View and Components

1.1 View

react-native자주쓰는 core components

  • 위 그림은 각각 Android와 iOS에서 화면을 그릴 때, 쓰는 컴포넌트들을 보여준다.

  • 리스트들 중에서 하나의 아이템을 표현할 때,

    • Android는 ViewGroup으로 감싸고, 그 안쪽 아이콘은 ImageView, 글자는 TextView 컴포넌트를 사용
    • iOS는 UIView으로 감싸고, 그 안쪽 아이콘은 UIImageView, 글자는 UITextView 컴포넌트를 사용
  • 그러면 React Native에서는 각 OS별 컴포넌트들을 어떤 걸로 대체해야 할까?

    • 바로 Native Component이다.
  • cf. https://reactnative.dev/docs/intro-react-native-components 


1.2 Native Component

Native Components: 플랫폼(iOS 또는 Android)의 view를 JS로 호출할 수 있게 해주는 React 컴포넌트

  • 코드를 작성할 땐, JavaScript와 React Component
  • Runtime에서 React Native가 구현한 코드에 상응하는 안드로이드와 iOS view를 생성함
  • 다른 사람이 만든 Native Component를 사용할 수도 있음: React Native Directory 

1.3 대표적인 Core Components

REACT NATIVE UI COMPONENTANDROID VIEWIOS VIEWWEB ANALOGDESCRIPTION
<View><ViewGroup><UIView>A non-scrolling <div>flexbox, 스타일, 일부 터치 처리, 접근성 컨트롤을 지원하는 컨테이너
<Text><TextView><UITextView><p>텍스트 문자열을 표시, 스타일링하고 중첩하며, 심지어 터치 이벤트를 처리
<Image><ImageView><UIImageView><img>다양한 유형의 이미지를 표시
<ScrollView><ScrollView><UIScrollView><div>여러 컴포넌트와 뷰를 포함할 수 있는 일반 스크롤 컨테이너
<TextInput><EditText><UITextField><input type="text">사용자가 텍스트를 입력할 수 있게 함

2. Core Components 예시

2.1 Text Input

tsx
1
import React, { useState } from 'react'
2
import { Text, TextInput, View } from 'react-native'
3
4
const PizzaTranslator = () => {
5
const [text, setText] = useState('')
6
7
return (
8
<View style={{ padding: 100 }}>
9
<TextInput
10
style={{ height: 40 }}
11
placeholder="Type here to translate!"
12
onChangeText={newText => setText(newText)}
13
defaultValue={text}
14
/>
15
<Text style={{ padding: 10, fontSize: 42 }}>
16
{text
17
.split(' ')
18
.map(word => word && '🍕')
19
.join(' ')}
20
</Text>
21
</View>
22
)
23
}
24
25
export default PizzaTranslator

2.2 Scroll View

tsx
1
import React from 'react'
2
import { Image, ScrollView, Text } from 'react-native'
3
4
const logo = {
5
uri: 'https://reactnative.dev/img/tiny_logo.png',
6
width: 64,
7
height: 64,
8
}
9
10
const App = () => (
11
<ScrollView>
12
<Text style={{ fontSize: 96 }}>Scroll me plz</Text>
13
<Image source={logo} />
14
<Image source={logo} />
15
<Image source={logo} />
16
<Image source={logo} />
17
<Image source={logo} />
18
<Text style={{ fontSize: 96 }}>If you like</Text>
19
<Image source={logo} />
20
<Image source={logo} />
21
<Image source={logo} />
22
<Image source={logo} />
23
<Image source={logo} />
24
<Text style={{ fontSize: 96 }}>Scrolling down</Text>
25
<Image source={logo} />
26
<Image source={logo} />
27
<Image source={logo} />
28
<Image source={logo} />
29
<Image source={logo} />
30
<Text style={{ fontSize: 96 }}>What's the best</Text>
31
<Image source={logo} />
32
<Image source={logo} />
33
<Image source={logo} />
34
<Image source={logo} />
35
<Image source={logo} />
36
<Text style={{ fontSize: 96 }}>Framework around?</Text>
37
<Image source={logo} />
38
<Image source={logo} />
39
<Image source={logo} />
40
<Image source={logo} />
41
<Image source={logo} />
42
<Text style={{ fontSize: 80 }}>React Native</Text>
43
</ScrollView>
44
)
45
46
export default App

iOS의 경우, ScrollView에서 줌이 가능하게 할 수 있음

  • maximumZoomScale: 최대 줌 스케일 설정
  • minimumZoomScale: 최소 줌 스케일 설정
tsx
1
<ScrollView minimumZoomScale={1.0} maximumZoomScale={2.0}>
2
<!-- ~~~ -->
3
</ScrollView>

iOS 시뮬레이터에서 pinch 줌을 하려면?

  • option키를 누르고 드래그

스크롤뷰는 화면에는 안보이는 아이템도 한번에 랜더링 해버림 → 많은 아이템이 있다면 랜더링 시간 길어짐


2.3 List View

2.3.1 FlatList

  • 화면에 현재 보이는 부분만 먼저 랜더링 됨
  • props 설명
    • data: 출력하고자 하는 모든 아이템들의 정보를 array(list) 형태로 전달
    • renderItem: 각 요소들을 어떤 포맷으로 출력할 것인지 구현하는 곳
    • keyExtractor: 각 아이템마다 unique한 key 값을 줌 (React에서의 key와 동일한 역할)
  • cf. https://reactnative.dev/docs/next/using-a-listview 
tsx
1
import React from 'react'
2
import { FlatList, StyleSheet, Text, View } from 'react-native'
3
4
const styles = StyleSheet.create({
5
container: {
6
flex: 1,
7
paddingTop: 22,
8
},
9
item: {
10
padding: 10,
11
fontSize: 18,
12
height: 44,
13
},
14
})
15
16
const FlatListBasics = () => {
17
return (
18
<View style={styles.container}>
19
<FlatList
20
data={[
21
{ key: 'Devin' },
22
{ key: 'Dan' },
23
{ key: 'Dominic' },
24
{ key: 'Jackson' },
25
{ key: 'James' },
26
{ key: 'Joel' },
27
{ key: 'John' },
28
{ key: 'Jillian' },
29
{ key: 'Jimmy' },
30
{ key: 'Julie' },
31
]}
32
renderItem={({ item }) => <Text style={styles.item}>{item.key}</Text>}
33
/>
34
</View>
35
)
36
}
37
38
export default FlatListBasics

2.3.2 SectionList

  • FlatList들을 구분할 수 있는 세션 헤더가 존재 (iOS의 UITableView와 비슷함)
  • props 설명
    • sections: 출력하고자 하는 모든 Section의 정보 를 array(list) 형태로 전달
      • (각 세션은 FlatList이기 때문에 FlatList의 props에 대한 정보를 정의해야 함)
    • renderItem: 각 아이템들을 어떤 포맷으로 출력할 것인지 구현하는 곳
    • renderSectionHeader: 세션을 구분하는 헤더를 구현하는 곳
    • keyExtractor: 각 아이템마다 unique한 key 값을 줌 (React에서의 key와 동일한 역할)
  • cf. https://reactnative.dev/docs/sectionlist 
tsx
1
import React from 'react'
2
import { StyleSheet, Text, View, SafeAreaView, SectionList, StatusBar } from 'react-native'
3
4
const DATA = [
5
{
6
title: 'Main dishes',
7
data: ['Pizza', 'Burger', 'Risotto'],
8
},
9
{
10
title: 'Sides',
11
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
12
},
13
{
14
title: 'Drinks',
15
data: ['Water', 'Coke', 'Beer'],
16
},
17
{
18
title: 'Desserts',
19
data: ['Cheese Cake', 'Ice Cream'],
20
},
21
]
22
23
const SectionListBasics = () => (
24
<SafeAreaView style={styles.container}>
25
<SectionList
26
sections={DATA}
27
keyExtractor={(item, index) => item + index}
28
renderItem={({ item }) => (
29
<View style={styles.item}>
30
<Text style={styles.title}>{item}</Text>
31
</View>
32
)}
33
renderSectionHeader={({ section: { title } }) => <Text style={styles.header}>{title}</Text>}
34
/>
35
</SafeAreaView>
36
)
37
38
const styles = StyleSheet.create({
39
container: {
40
flex: 1,
41
paddingTop: StatusBar.currentHeight,
42
marginHorizontal: 16,
43
},
44
item: {
45
backgroundColor: '#f9c2ff',
46
padding: 20,
47
marginVertical: 8,
48
},
49
header: {
50
fontSize: 32,
51
backgroundColor: '#fff',
52
},
53
title: {
54
fontSize: 24,
55
},
56
})
57
58
export default SectionListBasics