React Native의 스택, 탭 및 서랍 탐색을 React Navigation 5와 결합

이 기사에서는 다양한 유형의 탐색과 react-navigation 5를 사용하여 react-native에서 함께 결합하는 방법을 다룰 것입니다.

내용의 테이블


  • Prerequisite
  • Project Setup
  • Screens Setup
  • Installing Dependencies
  • Stack Navigator
  • Tab Navigator
  • Drawer Navigator
  • Conclusion

  • 전제 조건

    To be able to follow up with this article, you must have the following setup on your local environment

  • Node 설치됨.
  • 앱을 테스트하기 위한 에뮬레이터입니다. Android Studio 또는 Xcode 을 사용할 수 있습니다.

  • 프로젝트 설정

    To set up a react-native project, you can make use of the React Native CLI or the Expo CLI.

    I would be making use of the Expo CLI to set up a react-native project. To do so, run the following command on your terminal.

    npm install -g expo-cli
    

    The above command would install Expo CLI on your machine.

    Note: You need to have Node v12을 컴퓨터에 설치하여 명령줄을 사용하여 Expo CLI를 설치할 수 있습니다.

    위 명령어가 성공적으로 실행된 후 아래 명령어를 실행하여 react-native 프로젝트를 생성/생성합니다.

    expo init project-name
    

    위 명령이 성공적으로 실행되면 원하는 코드 편집기에서 프로젝트를 열고 터미널에서 npm start를 실행하여 애플리케이션을 시작합니다.

    To set up a react-native project using the React-Native CLI, check here.



    React 탐색 종속성 및 설정

    The dependencies below are the core utility used by the navigators to create the navigation structure, as well as our Stack, Tab, and Drawer navigation.

    In your project directory, run the command below on your terminal

    npm install @react-navigation/native @react-navigation/stack @react-navigation/bottom-tabs @react-navigation/drawer
    

    These dependencies below are the dependency relied upon for gestures, animations, and transitions. Also, run the command below on your terminal to install the dependencies.

    npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
    

    In the root file of our app, in this case, the App.js file, we would set up our react-navigation there.

    // ./App.js
    
    import React from "react";
    import { NavigationContainer } from "@react-navigation/native";
    
     const App = () => {
      return <NavigationContainer>{/* Navigation here */}</NavigationContainer>;
    }
    export default App;
    

    화면 설정

    The next step would be to set up screens that would be used in our application.

    I would be setting up 3 screens for the purpose of this demo, feel free to just copy them.

    So I'd set them up in a screens directory. Create a screens directory in the root of the project and add the components below

    Home Screen

    // ./screens/Home.js
    
    import React from "react";
    import { View, Button, Text, StyleSheet } from "react-native";
    
    const Home = () => {
      return (
        <View style={styles.center}>
          <Text>This is the home screen</Text>
          <Button title="Go to About Screen" />
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      center: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        textAlign: "center",
      },
    });
    
    export default Home;
    

    About Screen

    // ./screens/About.js
    
    import React from "react";
    import { View, StyleSheet, Text } from "react-native";
    
    const About = () => {
      return (
        <View style={styles.center}>
          <Text>This is the about screen</Text>
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      center: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        textAlign: "center",
      },
    });
    
    export default About;
    

    Contact Screen

    // ./screens/Contact.js
    
    import React from "react";
    import { View, StyleSheet, Text } from "react-native";
    
    const Contact = () => {
      return (
        <View style={styles.center}>
          <Text>This is the contact screen</Text>
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      center: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        textAlign: "center",
      },
    });
    
    export default Contact;
    

    스택 탐색

    Stack navigation provides a way for react-native apps to transition between screens by using a stack, which means the screens are stacked on each other.

    For example, if you navigate from login to signup screen, the signup screen is stacked on top of the login screen, and if you navigate back, the signup screen is then popped off the stack.

    To set up the stack navigation, I'd create a navigation directory at the root of our project. Inside our newly created directory, I'd also create a StackNavigator.js file in there, and add our stack navigation setup.

    Note: You can decide to name the folders and files however you want

    // ./navigation/StackNavigator.js
    
    import React from "react";
    import { createStackNavigator } from "@react-navigation/stack";
    
    import Home from "../screens/Home";
    import About from "../screens/About";
    
    const Stack = createStackNavigator();
    
    const MainStackNavigator = () => {
      return (
        <Stack.Navigator>
          <Stack.Screen name="Home" component={Home} />
          <Stack.Screen name="About" component={About} />
        </Stack.Navigator>
      );
    }
    
    export { MainStackNavigator };
    

    You can also customize and style the stack navigation by adding screenOptions prop style, see basic example below

    // ./navigation/StackNavigator.js
    
    const MainStackNavigator = () => {
      return (
        <Stack.Navigator
          screenOptions={{
            headerStyle: {
              backgroundColor: "#9AC4F8",
            },
            headerTintColor: "white",
            headerBackTitle: "Back",
          }}
        >
          <Stack.Screen name="Home" component={Home} />
          <Stack.Screen name="About" component={About} />
        </Stack.Navigator>
      );
    }
    

    Back in our App.js file, we can import and add our newly created Stack Navigator. So our App.js file would look like the code below

    // ./App.js
    
    import React from "react";
    import { NavigationContainer } from "@react-navigation/native";
    
    import { MainStackNavigator } from "./navigation/StackNavigator";
    
     const App = () => {
      return (
        <NavigationContainer>
          <MainStackNavigator />
        </NavigationContainer>
      );
    }
    export default App
    

    Now if we run the code on our emulator, We should now see our Home screen rendering on our Stack screens.



    ./screens/Home.js 파일에는 아무것도 하지 않는 버튼이 있었지만 스택 탐색 설정이 있으므로 이제 많은 작업을 수행하는 데 도움이 되는 스택 탐색에 의해 삽입된 탐색 소품에 액세스할 수 있습니다. 그 중 하나는 리디렉션입니다.

    따라서 ./screens/Home.js로 이동하여 아래 코드를 추가합니다.

    // ./screens/Home.js
    
    import React from "react";
    import { View, Button, Text, StyleSheet } from "react-native";
    
    const Home = ({ navigation }) => {
      return (
        <View style={styles.center}>
          <Text>This is the home screen</Text>
          <Button
            title="Go to About Screen"
            onPress={() => navigation.navigate("About")} // We added an onPress event which would navigate to the About screen
          />
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      center: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        textAlign: "center",
      },
    });
    
    export default Home;
    

    위의 코드에서 우리는 탐색 기능이 있는 개체인 탐색 소품을 가져옵니다. 이 개체는 버튼을 누른 후 탐색하려는 화면의 이름을 전달하여 호출합니다.



    이제 스택 탐색을 사용하여 화면 사이를 탐색할 수 있습니다.

    탭 탐색

    Tab navigation is a navigation that is tabbed at either the bottom or top of a screen and can be used to switch between different screens.

    Tab navigation can take in either the screen as a component or a Stack as the component.

    In our StackNavigator.js file, let's create another stack for our contact screen. So our StackNavigator.js will look like below

    // ./navigation/StackNavigator.js
    
    import React from "react";
    import { createStackNavigator } from "@react-navigation/stack";
    
    import Home from "../screens/Home";
    import About from "../screens/About";
    import Contact from "../screens/Contact";
    
    const Stack = createStackNavigator();
    
    const screenOptionStyle = {
      headerStyle: {
        backgroundColor: "#9AC4F8",
      },
      headerTintColor: "white",
      headerBackTitle: "Back",
    };
    
    const MainStackNavigator = () => {
      return (
        <Stack.Navigator screenOptions={screenOptionStyle}>
          <Stack.Screen name="Home" component={Home} />
          <Stack.Screen name="About" component={About} />
        </Stack.Navigator>
      );
    }
    
    const ContactStackNavigator = () => {
      return (
        <Stack.Navigator screenOptions={screenOptionStyle}>
          <Stack.Screen name="Contact" component={Contact} />
        </Stack.Navigator>
      );
    }
    
    export { MainStackNavigator, ContactStackNavigator };
    

    We can then create another file TabNavigator.js in the navigations directory and add the markup for our TabNavigator

    // ./navigation/TabNavigator.js
    
    import React from "react";
    import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
    
    import { MainStackNavigator, ContactStackNavigator } from "./StackNavigator";
    
    const Tab = createBottomTabNavigator();
    
    const BottomTabNavigator = () => {
      return (
        <Tab.Navigator>
          <Tab.Screen name="Home" component={MainStackNavigator} />
          <Tab.Screen name="Contact" component={ContactStackNavigator} />
        </Tab.Navigator>
      );
    };
    
    export default BottomTabNavigator;
    

    And then back in our App.js file, we can now import our newly created TabNavigator and use it there.

    //  ./App.js
    
    import React from "react";
    import { NavigationContainer } from "@react-navigation/native";
    
    import BottomTabNavigator from "./navigation/TabNavigator";
    
     const App = () => {
      return (
        <NavigationContainer>
          <BottomTabNavigator />
        </NavigationContainer>
      );
    }
    export default App
    


    서랍 탐색

    Drawer navigation is a slide-out and slide-in drawer that contains links to various screens. The Drawer navigation opens when a menu icon is clicked or when a user swipes their finger from the left or right edge of the app.

    In order to create drawer navigation, we would create another file in our navigations directory called DrawerNavigator.js

    In that file, we would add our drawer navigator markup

    // ./navigation/DrawerNavigator.js
    
    import React from "react";
    
    import { createDrawerNavigator } from "@react-navigation/drawer";
    
    import { ContactStackNavigator } from "./StackNavigator";
    import TabNavigator from "./TabNavigator";
    
    const Drawer = createDrawerNavigator();
    
    const DrawerNavigator = () => {
      return (
        <Drawer.Navigator>
          <Drawer.Screen name="Home" component={TabNavigator} />
          <Drawer.Screen name="Contact" component={ContactStackNavigator} />
        </Drawer.Navigator>
      );
    }
    
    export default DrawerNavigator;
    

    And then back in our App.js file, we can now import our newly created DrawerNavigtor.js file and use it as our navigator.

    // ./App.js
    
    import React from "react";
    import { NavigationContainer } from "@react-navigation/native";
    
    import DrawerNavigator from "./navigation/DrawerNavigator";
    
     const App = () => {
      return (
        <NavigationContainer>
          <DrawerNavigator />
        </NavigationContainer>
      );
    }
    export default App;
    


    서랍 탐색을 사용자 정의하기 위해 추가할 수 있는 구성 옵션 및 헤더 아이콘도 있습니다. 자세히 알아보기here .

    결론

    In this article, we've been able to look at how to set up and combine the Stack, Tab, and Drawer navigation for our react-native app using react-navigation 5.

    The source code used in demonstrating this article can be found here .

    이 기사에 대한 질문이나 피드백이 있으면 언제든지 의견을 남겨주십시오.

    읽어 주셔서 감사합니다.

    좋은 웹페이지 즐겨찾기