序章

React Navigation は、 ReactNativeアプリケーションでのルーティングとナビゲーションによく使用されるライブラリです。

このライブラリは、複数の画面間を移動したり、画面間でデータを共有したりする問題を解決するのに役立ちます。

このチュートリアルを終了すると、基本的なソーシャルネットワークができあがります。 ユーザーが持っている接続の数を表示し、追加の友達と接続する方法を提供します。 このサンプルアプリケーションを使用して、react-navigationを使用してモバイルアプリケーション画面をナビゲートする方法を探ります。

前提条件

このチュートリアルを完了するには、次のものが必要です。

注:過去にreact-navigationを使用したことがある場合は、いくつかの違いが発生する可能性があります。 3.xからの移行および4.xからの移行に関するガイドについてはドキュメントを参照してください。

このチュートリアルは、ノードv14.7.0、npm v6.14.7、react v16.13.1、react-native v0.63.2、@react-navigation/native v5.7.3、および@react-navigation/stackv5.9.0。

ステップ1—新しいReactNativeアプリを作成する

まず、ターミナルで次のコマンドを入力して、新しいReactNativeアプリを作成します。

  1. npx react-native init MySocialNetwork --version 0.63.2

次に、新しいディレクトリに移動します。

  1. cd MySocialNetwork

そして、iOS用のアプリケーションを起動します。

  1. npm run ios

または、Androidの場合:

  1. npm run android

注:問題が発生した場合は、 React NativeCLIのトラブルシューティングの問題を参照する必要がある場合があります。

これにより、スケルトンプロジェクトが作成されます。 今のところ、ソーシャルネットワークのようには見えません。 それを修正しましょう。

App.jsを開きます:

  1. nano App.js

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;

ファイルを保存します。 これで、アプリケーションを実行すると、 Welcome to MySocialNetwork!メッセージがシミュレーターに表示されます。

次のステップでは、アプリケーションにさらに画面を追加します。

ステップ2—HomeScreenおよびFriendsScreenを作成する

現在、ウェルカムメッセージを表示する単一の画面があります。 このステップでは、アプリケーション用にHomeScreenFriendsScreenの2つの画面を作成します。

HomeScreen

アプリにはHomeScreenが必要です。 HomeScreenには、ネットワークにすでに存在する友達の数が表示されます。

App.jsからコードを取得し、HomeScreen.jsという名前の新しいファイルに追加します。

  1. cp App.js HomeScreen.js

HomeScreen.jsを開きます:

  1. nano HomeScreen.js

Appの代わりにHomeScreenを使用するように、HomeScreen.jsを変更します。

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;

このコードは、あなたには(未定義の)友達がいます。プレースホルダーメッセージを生成します。 後で値を指定します。

FriendsScreen

アプリにはFriendsScreenも必要です。 FriendsScreenでは、新しい友達を追加できます。

App.jsからコードを取得し、FriendsScreen.jsという名前の新しいファイルに追加します。

  1. cp App.js FriendsScreen.js

FriendsScreen.jsを開きます:

  1. nano FriendsScreen.js

Appの代わりにFriendsScreenを使用するように、FriendsScreen.jsを変更します。

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;

このコードは、ここに友達を追加!メッセージを生成します。

この時点で、HomeScreenFriendsScreenがあります。 ただし、それらの間を移動する方法はありません。 次のステップでこの機能を構築します。

ステップ3—ReactNavigationでStackNavigatorを使用する

画面間を移動するには、StackNavigatorを使用します。 StackNavigatorは、コールスタックとまったく同じように機能します。 ナビゲートする各画面は、スタックの一番上にプッシュされます。 戻るボタンを押すたびに、画面がスタックの一番上から飛び出します。

まず、@react-navigation/nativeをインストールします。

  1. npm install @react-navigation/native@5.7.3

次に、@react-navigation/stackとそのピア依存関係をインストールします。

  1. 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に再度アクセスします。

  1. nano App.js

NavigationContainercreateStackNavigatorApp.jsに追加します。

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の内容を置き換えます。

App.js
// ...

class App extends React.Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator>
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

// ...

<Stack.Navigator>内にネストし、HomeScreenを追加します。

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';
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という1つの画面だけでナビゲーター用の非常に小さなスタックを作成します。

<Stack.Navigator>内にネストし、FriendsScreenを追加します。

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';
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をナビゲーターに追加します。

注:これは、以前のバージョンのReactNavigationでcreateStackNavigatorが使用されていた方法とは異なります。

これで、ナビゲーターは2つの画面を認識します。

HomeScreenおよびFriendsScreenへのボタンの追加

最後に、2つの画面の間に移動するボタンを追加します。

HomeScreen.jsに、次のコードを追加します。

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に、次のコードを追加します。

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 and FriendsScreen

ここでシミュレーターを開くと、HomeScreenFriendsScreenの間を移動できます。

ステップ4—Contextを使用してデータを他の画面に渡す

このステップでは、可能な友達の配列— AliceBob、およびSammy —と現在の友達の空の配列を作成します。 また、ユーザーが現在の友達に友達を追加するための機能を作成します。

App.jsを開きます:

  1. nano App.js

possibleFriendscurrentFriendsをコンポーネントの状態に追加します。

App.js
// ...

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      possibleFriends: [
        'Alice',
        'Bob',
        'Sammy',
      ],
      currentFriends: [],
    }
  }

  // ...
}

// ...

次に、可能性のある友達を現在の友達のリストに移動する関数を追加します。

App.js
// ...

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,
    })
  }

  // ...
}

// ...

この時点で、友達を追加する機能の構築が完了しました。

FriendsContextAppに追加

これで、App.jsに友達を追加できますが、FriendsScreen.jsに友達を追加して、HomeScreen.jsに表示することができます。 このプロジェクトはReactで構築されているため、コンテキストを使用してこの機能を画面に挿入できます。

注: React Navigationの以前のバージョンでは、screenPropsを使用して画面間でデータを共有することができました。 React Navigationの現在のバージョンでは、 ReactContextを使用して画面間でデータを共有することをお勧めします。

循環参照を回避するには、新しいFriendsContextファイルが必要になります。

  1. nano FriendsContext.js

エクスポートFriendsContext

FriendsContext
import React from 'react';

export const FriendsContext = React.createContext();

App.jsを開きます:

  1. nano App.js

FriendsContextを追加します。

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';
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を新しいコンテキストオブジェクトとして確立し、NavigationContainerContext.Providerコンポーネントにラップして、コンポーネントツリー内のすべての子がコンテキスト変更をサブスクライブできるようにします。 。

ViewまたはTextを使用しなくなったため、react-nativeからこれらのインポートを削除することができます。

消費者がデータにアクセスできるようにするには、valueを提供する必要があります。

App.js
// ...

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へのコンテキスト変更を参照できるようになります。

これで、画面内のコンテキストの参照に取り組むことができます。

FriendsContextHomeScreenに追加

このステップでは、現在の友達数を表示するようにアプリケーションを設定します。

HomeScreen.jsを開きます:

  1. nano HomeScreen.js

そして、FriendsContextを追加します。

HomeScreen.js
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を確立します。 これで、画面のコンテキストにアクセスできます。

たとえば、HomeScreencurrentFriendsの数を表示させましょう。

HomeScreen.js
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を表示すると、友達が0人です!というメッセージが表示されます。

FriendsContextFriendsScreenに追加

このステップでは、可能性のある友達を表示し、現在の友達に追加するためのボタンを提供するようにアプリケーションを設定します。

次に、FriendsScreen.jsを開きます。

  1. nano FriendsScreen.js

そして、FriendsContextを追加します。

FriendsScreen.js
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に友達を追加するためのボタンを作成します。

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を表示すると、追加する友達のリストが表示されます。

HomeScreen with 0 currentFriends and FriendScreen with 3 possibleFriends

FriendsScreenにアクセスし、ボタンをクリックして友達を追加すると、possibleFriendsのリストが減少します。 HomeScreenにアクセスすると、友達の数が増えます。

これで、画面間を移動して、画面間でデータを共有できます。

結論

このチュートリアルでは、複数の画面を備えたサンプルのReactNativeアプリケーションを作成しました。 React Navigationを使用して、画面間を移動する方法を考案しました。 React Contextを使用して、画面間でデータを共有する方法を開発しました。

このチュートリアルの完全なソースコードは、GitHubで入手できます。

React Navigationをさらに深く掘り下げたい場合は、それらのドキュメントをチェックしてください。

React Navigationは、ルーティングおよびナビゲーションソリューションだけではありません。 React Native Navigation React Native Router Flux 、および React RouterNativeもあります。

Reactの詳細については、 React.js シリーズのコーディング方法をご覧になるか、Reactトピックページで演習やプログラミングプロジェクトを確認してください。