LoginSignup
2
1

More than 5 years have passed since last update.

React-navigation

Posted at

react-navigationを使ったルーティング

パッケージをプロジェクトにaddする

yarn add react-navigation or npm install react-navigation --save

どういうもの?

React Navigation's StackNavigator provides a way for your app to transition between screens and manage navigation history.
react navigationのStackNavigatorはアプリ内の画面の移動と、そのhistoryを管理してくれるもの。(今はStackNavigatorしか使わないので他はわからない)

基本

navigationSimple
import React from 'react';
import { View, Text } from 'react-native';
import { StackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
      </View>
    );
  }
}

export default StackNavigator({
  Home: {
    screen: HomeScreen,
  },
});

公式ではStackNavigatorがcreateStackNavigatorになっているが、使えない

複数の画面のルーティング

navigationMulti
import React from 'react';
import { View, Text, Button } from 'react-native';
import { StackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
    render() {
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text>Home Screen</Text>
                <Button title="go detail" onPress={() => this.props.navigation.navigate('Detail')} />
            </View>
        );
    }
}
class DetailScreen extends React.Component {
    render() {
        return (
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text>detail Screen</Text>
                <Button title="go back" onPress={() => this.props.navigation.goBack()} />
            </View>
        );
    }
}

const RootStack = StackNavigator({
    Home: {
        screen: HomeScreen,
    },
    Detail: {
        screen: DetailScreen
    }
}, {
        initialRouteName: "Home"
    }
);

export default class App extends React.Component {
    render() {
        return <RootStack />
    }
}

オブジェクトのkeyがRoute名となり、その名前を使って行ったり来たりする。
initialRouteNameによってデフォルトの画面を決める(ない場合0番目の要素がデフォルトとなる)

画面移動は this.props.navigation....を使う
-特定の場所に行く場合: this.props.navigation.navigate(RouteName)
-戻る場合: this.props.navigation.goBack()

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1