React Native에서 React Navigation으로 라우팅을 사용하는 방법
소개
기본 애플리케이션에 반응합니다.
이 라이브러리는 여러 화면 사이를 탐색하고 화면 간에 데이터를 공유하는 문제를 해결하는 데 도움이 됩니다.
이 튜토리얼을 마치면 기초적인 소셜 네트워크를 갖게 됩니다. 사용자가 보유한 연결 수를 표시하고 추가 친구와 연결할 수 있는 방법을 제공합니다. 이 샘플 애플리케이션을 사용하여 react-navigation
을 사용하여 모바일 애플리케이션 화면을 탐색하는 방법을 탐색합니다.
전제 조건
이 자습서를 완료하려면 다음이 필요합니다.
- Node.js용 로컬 개발 환경입니다. Node.js 설치 및 로컬 개발 환경 생성 방법을 따르십시오.
- 새로운 React Native 프로젝트를 생성하고 iOS 또는 Android 시뮬레이터를 사용하기 위한 환경 설정에 익숙하면 도움이 될 수 있습니다.
참고: 이전에 react-navigation
작업을 했다면 약간의 차이가 발생할 수 있습니다. 4.x에서 마이그레이션하는 방법에 대한 설명서를 참조할 수 있습니다.
이 튜토리얼은 Node v14.7.0, npm
v6.14.7, react
v16.13.1, react-native
v0.63.2, @react-navigation/native
v5.7.3 및 @react-navigation/stack
v5.9.0.
1단계 — 새 React Native 앱 만들기
먼저 터미널에 다음 명령을 입력하여 새 React Native 앱을 만듭니다.
- npx react-native init MySocialNetwork --version 0.63.2
그런 다음 새 디렉터리로 이동합니다.
- cd MySocialNetwork
그리고 iOS용 애플리케이션을 시작합니다.
- npm run ios
또는 Android의 경우:
- npm run android
참고: 문제가 발생하면 React Native CLI에 대한 문제 해결 문제를 참조해야 할 수 있습니다.
이렇게 하면 스켈레톤 프로젝트가 생성됩니다. 지금은 소셜 네트워크처럼 보이지 않습니다. 수정합시다.
App.js
를 엽니다.
- nano App.js
환영 메시지를 표시하려면 App.js
의 내용을 다음 코드로 바꿉니다.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Welcome to MySocialNetwork!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default App;
파일을 저장합니다. 이제 애플리케이션을 실행하면 MySocialNetwork에 오신 것을 환영합니다! 메시지가 시뮬레이터에 나타납니다.
다음 단계에서는 애플리케이션에 더 많은 화면을 추가합니다.
2단계 - HomeScreen 및 FriendsScreen 만들기
현재 환영 메시지를 표시하는 단일 화면이 있습니다. 이 단계에서는 애플리케이션에 대한 두 개의 화면인 HomeScreen
및 FriendsScreen
을 생성합니다.
홈 화면
앱에 HomeScreen
이 필요합니다. 홈 화면
은 네트워크에 이미 있는 친구의 수를 표시합니다.
App.js
에서 코드를 가져와 HomeScreen.js
라는 새 파일에 추가합니다.
- cp App.js HomeScreen.js
HomeScreen.js
를 엽니다.
- nano HomeScreen.js
App
대신 HomeScreen
을 사용하도록 HomeScreen.js
를 수정합니다.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
class HomeScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>You have (undefined) friends.</Text>
</View>
);
}
}
// ...
export default HomeScreen;
이 코드는 You have (undefined) friends를 생성합니다. 자리 표시자 메시지. 나중에 값을 제공합니다.
친구화면
앱에는 FriendsScreen
도 필요합니다. FriendsScreen
에서 새 친구를 추가할 수 있습니다.
App.js
에서 코드를 가져와 FriendsScreen.js
라는 새 파일에 추가합니다.
- cp App.js FriendsScreen.js
FriendsScreen.js
열기:
- nano FriendsScreen.js
App
대신 FriendsScreen
을 사용하도록 FriendsScreen.js
를 수정합니다.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
class FriendsScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Add friends here!</Text>
</View>
);
}
}
// ...
export default FriendsScreen;
이 코드는 여기에 친구 추가를 생성합니다! 메시지.
이 시점에서 HomeScreen
및 FriendsScreen
이 있습니다. 그러나 그들 사이를 탐색할 수 있는 방법은 없습니다. 다음 단계에서 이 기능을 빌드합니다.
3단계 — React Navigation과 함께 StackNavigator 사용
화면 간 탐색을 위해 StackNavigator
를 사용합니다. StackNavigator
는 호출 스택과 똑같이 작동합니다. 탐색하는 각 화면은 스택 맨 위로 푸시됩니다. 뒤로 버튼을 누를 때마다 화면이 스택 맨 위에서 튀어나옵니다.
먼저 @react-navigation/native
를 설치합니다.
- npm install @react-navigation/native@5.7.3
그런 다음 @react-navigation/stack
및 해당 피어 종속성을 설치합니다.
- npm install @react-navigation/stack@5.9.0 @react-native-community/masked-view@0.1.10 react-native-screens@2.10.1 react-native-safe-area-context@3.1.4 react-native-gesture-handler@1.7.0
참고: iOS용으로 개발 중인 경우 ios
디렉토리로 이동하여 pod install
을 실행해야 할 수 있습니다.
다음으로 App.js
를 다시 방문합니다.
- nano App.js
NavigationContainer
및 createStackNavigator
를 App.js
에 추가합니다.
import 'react-native-gesture-handler';
import React from 'react';
import { StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
그런 다음 render
의 내용을 바꿉니다.
// ...
class App extends React.Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator>
</Stack.Navigator>
</NavigationContainer>
);
}
}
// ...
내부에 중첩되어 HomeScreen
을 추가합니다.
import 'react-native-gesture-handler';
import React from 'react';
import { StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './HomeScreen';
const Stack = createStackNavigator();
class App extends React.Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
}
// ...
이 코드는 하나의 화면(HomeScreen
)만 있는 네비게이터용 매우 작은 스택을 생성합니다.
내부에 중첩되어 FriendsScreen
을 추가합니다.
import 'react-native-gesture-handler';
import React from 'react';
import { StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './HomeScreen';
import FriendsScreen from './FriendsScreen';
const Stack = createStackNavigator();
class App extends React.Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
/>
<Stack.Screen
name="Friends"
component={FriendsScreen}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
}
// ...
이 코드는 FriendsScreen
을 탐색기에 추가합니다.
참고: 이는 이전 버전의 React Navigation에서 createStackNavigator
가 사용된 방식과 다릅니다.
이제 내비게이터는 두 화면을 인식합니다.
HomeScreen 및 FriendsScreen에 버튼 추가
마지막으로 두 화면 사이를 이동할 수 있는 버튼을 추가합니다.
HomeScreen.js
에서 다음 코드를 추가합니다.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
class HomeScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>You have (undefined) friends.</Text>
<Button
title="Add some friends"
onPress={() =>
this.props.navigation.navigate('Friends')
}
/>
</View>
);
}
}
// ...
FriendsScreen.js
에서 다음 코드를 추가합니다.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
class FriendsScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Add friends here!</Text>
<Button
title="Back to home"
onPress={() =>
this.props.navigation.navigate('Home')
}
/>
</View>
);
}
}
// ...
this.props.navigation
에 대해 이야기해 봅시다. 화면이 StackNavigator
에 포함되어 있는 한 navigation
개체에서 많은 유용한 소품을 자동으로 상속합니다. 이 경우 navigate
를 사용하여 다른 페이지로 이동했습니다.
지금 시뮬레이터를 열면 HomeScreen
과 FriendsScreen
사이를 탐색할 수 있습니다.
4단계 - 컨텍스트를 사용하여 다른 화면으로 데이터 전달
이 단계에서는 Alice
, Bob
및 Sammy
와 같은 가능한 친구 배열과 현재 친구의 빈 배열을 만듭니다. 또한 사용자가 가능한 친구를 현재 친구에 추가하는 기능을 만들 것입니다.
App.js
를 엽니다.
- nano App.js
구성 요소의 상태에 possibleFriends
및 currentFriends
를 추가합니다.
// ...
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
possibleFriends: [
'Alice',
'Bob',
'Sammy',
],
currentFriends: [],
}
}
// ...
}
// ...
다음으로 가능한 친구를 현재 친구 목록으로 이동하는 기능을 추가합니다.
// ...
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
possibleFriends: [
'Alice',
'Bob',
'Sammy',
],
currentFriends: [],
}
}
addFriend = (index) => {
const {
currentFriends,
possibleFriends,
} = this.state
// Pull friend out of possibleFriends
const addedFriend = possibleFriends.splice(index, 1)
// And put friend in currentFriends
currentFriends.push(addedFriend)
// Finally, update the app state
this.setState({
currentFriends,
possibleFriends,
})
}
// ...
}
// ...
이 시점에서 친구 추가 기능 구축을 완료했습니다.
앱에 FriendsContext 추가
이제 App.js
에 친구를 추가할 수 있지만 FriendsScreen.js
에 친구를 추가하고 HomeScreen.js
에 표시되도록 할 수 있습니다. . 이 프로젝트는 React로 빌드되었으므로 이 기능을 컨텍스트와 함께 화면에 삽입할 수 있습니다.
참고: 이전 버전의 React Navigation에서는 screenProps
를 사용하여 화면 간에 데이터를 공유할 수 있었습니다. 현재 버전의 React Navigation에서는 React Context를 사용하여 화면 간 데이터 공유를 권장합니다.
순환 참조를 피하려면 새 FriendsContext
파일이 필요합니다.
- nano FriendsContext.js
FriendsContext
내보내기:
import React from 'react';
export const FriendsContext = React.createContext();
App.js
를 엽니다.
- nano App.js
FriendsContext
를 추가합니다.
import 'react-native-gesture-handler';
import React from 'react';
import { StyleSheet } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { FriendsContext } from './FriendsContext';
import Home from './Home';
import Friends from './Friends';
const Stack = createStackNavigator();
class App extends React.Component {
// ...
render() {
return (
<FriendsContext.Provider>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}
/>
<Stack.Screen
name="Friends"
component={Friends}
/>
</Stack.Navigator>
</NavigationContainer>
</FriendsContext.Provider>
);
}
}
// ...
이 코드는 FriendsContext
를 새 Context
개체로 설정하고 NavigationContainer
를 Context.Provider
구성 요소로 래핑하여 구성 요소 트리에서 컨텍스트 변경을 구독할 수 있습니다.
더 이상 View
또는 Text
를 사용하지 않으므로 react-native
에서 이러한 가져오기를 제거할 수 있습니다.
소비자가 데이터에 액세스할 수 있도록 하려면 값
을 제공해야 합니다.
// ...
class App extends React.Component {
// ...
render() {
return (
<FriendsContext.Provider
value={
{
currentFriends: this.state.currentFriends,
possibleFriends: this.state.possibleFriends,
addFriend: this.addFriend
}
}
>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}
/>
<Stack.Screen
name="Friends"
component={Friends}
/>
</Stack.Navigator>
</NavigationContainer>
</FriendsContext.Provider>
);
}
}
// ...
이렇게 하면 HomeScreen
및 FriendsScreen
이 currentFriends
및 possibleFriends
에 대한 컨텍스트 변경을 참조할 수 있습니다.
이제 화면에서 컨텍스트를 참조할 수 있습니다.
HomeScreen에 FriendsContext 추가
이 단계에서는 현재 친구 수를 표시하도록 애플리케이션을 설정합니다.
HomeScreen.js
를 엽니다.
- nano HomeScreen.js
그리고 FriendsContext
를 추가합니다.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { FriendsContext } from './FriendsContext';
class HomeScreen extends React.Component {
// ...
}
HomeScreen.contextType = FriendsContext;
// ...
이 코드는 Class.contextType
을 설정합니다. 이제 화면에서 컨텍스트에 액세스할 수 있습니다.
예를 들어 HomeScreen
에 현재 가지고 있는 currentFriends
의 수를 표시하도록 합시다.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { FriendsContext } from './FriendsContext';
class Home extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>You have { this.context.currentFriends.length } friends!</Text>
<Button
title="Add some friends"
onPress={() =>
this.props.navigation.navigate('Friends')
}
/>
</View>
);
}
}
HomeScreen.contextType = FriendsContext;
// ...
시뮬레이터에서 앱을 다시 열고 HomeScreen
을 보면 다음 메시지가 표시됩니다. You have 0 friends!.
FriendsScreen에 FriendsContext 추가하기
이 단계에서는 가능한 친구를 표시하고 현재 친구에 추가하기 위한 버튼을 제공하도록 애플리케이션을 설정합니다.
다음으로 FriendsScreen.js
를 엽니다.
- nano FriendsScreen.js
그리고 FriendsContext
를 추가합니다.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { FriendsContext } from './FriendsContext';
class FriendsScreen extends React.Component {
// ...
}
FriendsScreen.contextType = FriendsContext;
// ...
이 코드는 Class.contextType
을 설정합니다.
이제 FriendsScreen.js
에서 친구를 추가하는 버튼을 만듭니다.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { FriendsContext } from './FriendsContext';
class Friends extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Add friends here!</Text>
{
this.context.possibleFriends.map((friend, index) => (
<Button
key={ friend }
title={ `Add ${ friend }` }
onPress={() =>
this.context.addFriend(index)
}
/>
))
}
<Button
title="Back to home"
onPress={() =>
this.props.navigation.navigate('Home')
}
/>
</View>
);
}
}
FriendsScreen.contextType = FriendsContext;
// ...
시뮬레이터에서 앱을 다시 열고 FriendsScreen
을 보면 추가할 친구 목록이 표시됩니다.
친구화면
에 접속하여 친구 추가 버튼을 클릭하면 가능한 친구
목록이 줄어드는 것을 볼 수 있습니다. 홈 화면
을 방문하면 친구 수가 늘어나는 것을 볼 수 있습니다.
이제 화면 사이를 탐색하고 화면 간에 데이터를 공유할 수 있습니다.
결론
이 자습서에서는 여러 화면이 있는 샘플 React Native 애플리케이션을 만들었습니다. React Navigation을 사용하여 화면 사이를 탐색하는 방법을 고안했습니다. React Context를 사용하여 화면 간에 데이터를 공유하는 방법을 개발했습니다.
이 자습서의 전체 소스 코드는 GitHub에서 사용할 수 있습니다.
React Navigation에 대해 더 자세히 알고 싶다면 설명서를 확인하세요.
React Navigation이 유일한 라우팅 및 탐색 솔루션은 아닙니다. React Router Native도 있습니다.
React에 대해 자세히 알아보려면 연습 및 프로그래밍 프로젝트에 대한 React 주제 페이지를 살펴보세요.