Computer >> 컴퓨터 >  >> 스마트폰 >> iPhone

react-navigation 5를 사용하여 React Native에서 탐색을 처리하는 방법

React-navigation은 React Native에서 탐색에 대해 이야기할 때 생각나는 탐색 라이브러리입니다.

저는 이 라이브러리의 열렬한 팬이며 항상 React Native에서 탐색을 처리하는 데 사용하는 첫 번째 솔루션입니다. 이것은 부분적으로 훌륭하고 쉬운 API를 가지고 있고 매우 사용자 정의할 수 있기 때문입니다.

버전 5가 베타에서 안정 버전으로 바뀌었기 때문에 이 기사를 쓰고 있습니다. 일부 기능 변경 및 경로를 선언하는 간단하고 다른 방법을 제공하는 새로운 API 디자인과 함께 제공됩니다.

이 기사에서는 새로운 API를 살펴보고 애플리케이션에서 이를 사용하는 방법을 살펴보겠습니다.

<블록 인용>

원래 sayhayani.com에 게시됨

설치 중

react-navigation을 설치하는 방법이 이전 버전(>4.x)에 비해 약간 변경되었습니다.

// > 4.x verions
yarn add react-navigation

react-navigation 5를 설치하면 다음과 같습니다.

// yarn
yarn add @react-navigation/native
// npm
npm install @react-navigation/native

최신 버전의 react-navigation은 애니메이션 및 전환 처리를 위해 react-native-gesture-handler와 같은 많은 타사 라이브러리를 사용합니다. 따라서 항상 해당 라이브러리를 설치해야 합니다.

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

동적 화면

새 API는 경로 초기화에 역동성을 도입합니다. 이전에는 정적으로 수행되었습니다. 기본적으로 구성 파일에서 경로를 정의해야 했습니다.

// @flow
import React from "react";

import { createAppContainer, createSwitchNavigator } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";


/** ---------Screens----------- */
// import LaunchScreen from "../Containers/LaunchScreen";
import HomeScreen from "../Containers/HomeScreen";

import ProfileScreen from "../Containers/ProfileScreen";
import LoginScreen from "../Containers/LoginScreen";






const StackNavigator = createStackNavigator(
  {
    initialRouteName: "Home"
  },
  {
    Home: {
      screen: HomeScreen
    },
     Login: {
      screen: LoginScreen,
      headerMode: "none",

    },
      Profile: {
      screen: ProfileScreen
    }



);

export default createAppContainer(StackNavigator);

새 API는 동적 구성 요소와 함께 제공됩니다. 탐색을 보다 역동적으로 만들었습니다.
Route를 선언하는 새로운 방법은 다음과 같습니다.

import React from "react"
import { SafeAreaView, StyleSheet, View, Text, StatusBar } from "react-native"

import { NavigationContainer } from "@react-navigation/native"
import { createStackNavigator } from "@react-navigation/stack"

const App: () => React$Node = () => {
  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView style={styles.containerStyle}>
        <AppNavigation />
      </SafeAreaView>
    </>
  )
}
const Stack = createStackNavigator()
const AppNavigation = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="home">
        <Stack.Screen name="home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}
const HomeScreen = () => {
  return (
    <View style={styles.containerStyle}>
      <Text style={styles.title}>Home Screen</Text>
    </View>
  )
}

react-navigation 5를 사용하여 React Native에서 탐색을 처리하는 방법

이 새로운 방식은 동적이고 사용이 간편하며 react-router API와 비슷합니다.

동적 옵션

이것은 커뮤니티에서 오랫동안 가장 많이 요청한 기능입니다. 예전 방식(정적)에 항상 문제가 있었고 탐색 동작을 동적으로 변경하는 것이 정말 어려웠습니다.

이전 방법 => <4.x

이전 버전의 반응 탐색에서는 정적 옵션을 정의해야 했습니다. 그리고 이것을 동적으로 변경할 방법이 없었습니다.

  static navigationOptions = {
    title: "Sign In",
    header: null,
    mode: "modal",
    headerMode: "none"
  };

새로운 방법(버전 5)

React-navigation은 매우 간단한 동적 방법과 함께 제공됩니다. props만 사용하여 모든 화면에 옵션을 설정할 수 있습니다. .

const AppNavigation = ({}) => {
  let auth = {
    authenticated: true,
    user: {
      email: "user@mail.com",
      username: "John",
    },
  }
  let ProfileScreenTitle = auth.authenticated ? auth.user.username : "Profile"
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen
          name="Profile"
          component={ProfileScreen}
          options={{
            title: ProfileScreenTitle,
            headerTintColor: "#4aa3ba",
            headerStyle: {
              backgroundColor: darkModeOn ? "#000" : "#fff",
            },
          }}
        />
        <Stack.Screen name="About" component={AboutScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

react-navigation 5를 사용하여 React Native에서 탐색을 처리하는 방법

동적 옵션을 사용하면 인증에 따라 제목을 변경할 수 있습니다. 예를 들어 사용자가 인증되면 화면 제목을 사용자의 사용자 이름으로 설정하거나 헤더의 backgroundColor를 변경할 수 있습니다.

이는 동적 테마를 사용하거나 앱에서 다크 모드를 구현하려는 경우에 특히 유용합니다.

후크

이것은 지금까지 내가 가장 좋아하는 기능이며 시간을 절약해 줍니다. 새 API에는 특정 작업을 수행하기 위한 몇 가지 사용자 지정 후크가 도입되었습니다.

예를 들어 이전 버전에서는 활성 화면의 currentName을 가져와야 하는 경우 다음과 같이 이를 수행하는 도우미를 만들어야 했습니다.

export function getCurrentRouteName(): string | null {
  const tag = "[getCurrentRouteNameSync] "
  const navState = getStore().getState().nav
  const currentRoute = getActiveRouteState(navState)
  console.log(tag + " currentRoute > ", currentRoute)
  return currentRoute && currentRoute.routeName ? currentRoute.routeName : null
}

후크 API를 사용하면 이러한 모든 것을 피할 수 있고 후크를 사용하여 한 줄로 Navigation API에 더 쉽게 액세스할 수 있습니다.

이제 useRoute을 사용하여 RouteName을 쉽게 얻을 수 있습니다. 후크.

import { useRoute } from "@react-navigation/native"
const AboutScreen = ({ navigation }) => {
  const route = useRoute()
  return (
    <View
      style={{
        justifyContent: "space-around",
        flex: 1,
        alignItems: "center",
      }}
    >
      {/*    Display the RouteName here */}
      <Text style={styles.title}>{route.name}</Text>
    </View>
  )
}

useNavigationState로 동일한 작업을 수행할 수 있습니다. 훅. 탐색 상태에 대한 액세스를 제공합니다.

const navigationState = useNavigationState(state => state)
let index = navigationState.index
let routes = navigationState.routes.length
console.log(index)
console.log(routes)

React-navigation은 다음과 같은 다른 후크도 제공합니다.

  • useFocuseEffect :화면이 로드될 때 초점이 맞춰진 화면을 반환하는 사이드 이펙트 후크
  • useLinking :딥링크 처리

나는 당신이 그들을 확인하는 것이 좋습니다.

마무리

새로운 반응 탐색 API는 확실히 정적에서 동적으로 이동합니다. React Native에서 탐색을 처리하는 방식을 완전히 바꿀 훌륭한 방향입니다. 동적 경로는 반응 탐색 사용자의 주요 요청이었고 이 새로운 방법은 더 나은 사용자 탐색 경험을 만드는 데 도움이 될 것입니다.

여기에서 React Native에 대한 자세한 내용을 찾을 수 있습니다.

<블록 인용>

읽어주셔서 감사합니다

  • 트위터
  • 깃허브
  • 메일 목록에 가입
프로젝트를 위한 React Native 개발자를 찾고 계십니까? 나를 때려줘 .