컴포넌트란 재사용이 가능한 조립 블록으로 화면에 나타나는 UI요소이다.
지금까지 봤던 App.js 파일도 App이라는 컴포넌트이다.
컴포넌트는 단순히 UI 역할만 하는 것이 아니라 부모로부터 받은 props이나 자신의 state에 따라 표현이 달라지고 다양한 기능을 수행한다.
즉 컴포넌트는 데이터와 UI 요소의 집합체라고 할 수 있다.
1. 내장 컴포넌트
Button 컴포넌트를 사용하고 title과 onPress 속성을 지정해 보자.
title 속성은 버튼 내부에 출력되는 텍스트이며, onPress 속성에는 버튼이 눌렸을 때 호출되는 함수를 지정할 수 있다.
src폴더를 생성하고 App 컴포넌트를 작성할 App.js파일을 생성한다.
src/App.js
import React from "react";
import { View, Button, Text } 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("Click!")} />
</View>
);
};
export default App;
App.js
import App from "./src/App";
export default App;
2. 커스텀 컴포넌트 만들기
리액트 네이티브에서 다양한 컴포넌트들을 제공하고 있다, 하지만 프로젝트를 진행하다 보면 여러 컴포넌트를 조합해서 새로운 컴포넌트를 제작하여 사용하게 된다.
내장된 컴포넌트를 사용하게 되면 iOS와 안드로이드에서 다른 모습으로 렌더링 된다는 단점이 있다.
그 단점을 보완하기 위해 TouchableOpacity 컴포넌트와 Text 컴포넌트를 이용해서 Button 컴포넌트를 대체할 MyButton 컴포넌트를 만들어보자.
src/components/MyButton.js
import React from "react";
import { TouchableOpacity, Text } from "react-native";
const MyButton = () => {
return (
<TouchableOpacity>
<Text style={{ fontSize: 24 }}>My Button</Text>
</TouchableOpacity>
);
};
export default MyButton;
src/App.js
import React from "react";
import { View, Text } from "react-native";
import MyButton from "./components/MyButton";
const App = () => {
return (
<View
style={{
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
}}
>
<Text style={{ fontSize: 30, marginBottom: 10 }}>
My Button Component
</Text>
<MyButton />
</View>
);
};
export default App;
버튼이 생성이 되긴 하였지만 더 버튼처럼 보이도록 스타일을 수정하고 클릭에 대한 행동을 설정해 보자!
src/components/MyButton.js
import React from "react";
import { TouchableOpacity, Text } from "react-native";
const MyButton = () => {
return (
<TouchableOpacity
style={{
backgroundColor: "#3498db",
padding: 16,
margin: 10,
borderRadius: 8,
}}
onPress={() => alert("Click!")}
>
<Text style={{ fontSize: 24, color: "white" }}>My Button</Text>
</TouchableOpacity>
);
};
export default MyButton;
커스텀 컴포넌트를 사용하여 내장 컴포넌트의 단점을 해결할 수 있었다!
'React-Native' 카테고리의 다른 글
6) React-Native 스타일링 (4) | 2024.10.24 |
---|---|
5) React-Native 이벤트 (1) | 2024.10.23 |
4) React-Native Props와 State (0) | 2024.10.23 |
2) React-Native JSX (0) | 2024.10.23 |
1) 리액트 네이티브란 (4) | 2024.10.23 |