본문 바로가기
Hybrid/React Native

리액트 네이티브 ] 3. 컴포넌트

by 김마리님 2021. 10. 2.

(책 : 처음 배우는 리액트 네이티브)

 

컴포넌트는 재사용이 가능한 조립블럭이다. 컴포넌트는 단순히 UI만을 표기하는 것이 아니라 부모의 속성, 자신의 상태에 따라 표현이 달라지고 다양한 기능을 수행한다. 리액트 네이티브는 이 컴포넌트를 통해 화면을 구성한다.

 

리액트 네이티브는 다양한 내장 컴포넌트를 제공한다. 해당 컴포넌트는 리액트 네이티브 개발자 문서에 다 나와있다.

https://reactnative.dev/docs/getting-started

 

Introduction · React Native

This helpful guide lays out the prerequisites for learning React Native, using these docs, and setting up your environment.

reactnative.dev

 

내장 컴포넌트 예시를 보자.

 

Button이라는 내장 컴포넌트가 있다.

이걸 한번 써보자.

 

-../src/App.js

import React from "react";
import { View, Text, Button } from "react-native";

const App = () => {
    return (
        <View style={{
            flex: 1,
            backgroundColor: '#fff',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <Text style={{fontSize : 30, marginBottom : 10}}>Button Component</Text>
            <Button title="Button" onPress={()=> alert("alert")}></Button>
        
          </View>
    );
}

export default App;

 

-App.js

import App from './src/App'

export default App;

 

결과물을 보자.

(안드로이드와 아이폰 비교)

 

그런데 같은 코드를 써도 버튼이 서로 다른 디자인을 가지고 있는 것을 알 수 있다. 이건 안드로이드와 아이폰이 서로 다른 컴포넌트 디자인을 가지고 있기 때문인데, 그렇기 때문에 보통은 내장 컴포넌트가 아닌 커스텀 컴포넌트를 사용한다.

 

 

-../component/myButton.js

import React from "react";
import { Pressable, Text, TouchableOpacity } from "react-native";

const MyButton = () => {
    return (
        <Pressable
        style = {{
            backgroundColor : '#aaaaaa',
            padding : 16,
            margin: 10,
            borderRadius : 5,
        }}
        onPress = {() => alert("click")}>
            <Text style={{fontSize : 24, color : '#ffffff'}}>Button</Text>
        </Pressable>
    );
};

export default MyButton;

저만 그런지 잘 모르겠는데, 커스텀 컴포넌트 함수의 시작이 대문자여야 인식을 하더라고요. 자바코틀린 하던 습관적으로 앞 문자를 소문자로 하니까 뷰 인식을 못하고 에러가 뜨던데, 

위에 임포트 부분 보면 인식 못하는게 보이시죠?

실제로 구동 시켜보면,

진짜 오류가 뜹니다. 그러니까 커스텀 컴포넌트 선언시 반드시 대문자를 시작으로 쓰기!

 

이제 만든 컴포넌트를 사용해보자.

import React from "react";
import { View, Text, Button } from "react-native";
import MyButton from "../component/myButton";

const App = () => {
    return (
        <View style={{
            flex: 1,
            backgroundColor: '#fff',
            alignItems: 'center',
            justifyContent: 'center',
          }}>
            <Text style={{fontSize : 30, marginBottom : 10}}>Button Component</Text>
            <MyButton />
          </View>
    );
}

export default App;

 

확인해봅시다.

 

두 버튼 이미지가 동일해진 것을 볼 수 있다.

 

반응형