1. ก่อนอื่นเราจะต้องนำหน้าที่ต้องการ Navigate ไปเก็บไว้ที่ Stack Navigator ก่อน
App.js
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import configureStore from './src/configureStore'; import Login from './Login'; import MyIndex from './pages/MyIndex'; import ImageBrowserScreen from './components/ImageBrowserScreen'; import { navigationRef } from './RootNavigation'; import {createStackNavigator} from '@react-navigation/stack'; import {NavigationContainer,useIsFocused} from '@react-navigation/native'; const Stack = createStackNavigator(); const store = configureStore(); export default class App extends Component { constructor(props){ super(props); } render() { return ( <Provider store={store}> <NavigationContainer ref={navigationRef} > <Stack.Navigator screenOptions={{headerShown:false }} > <Stack.Screen name="Login" component={Login} /> <Stack.Screen name="MyIndex" component={MyIndex} /> <Stack.Screen name="ImageBrowser" component={ImageBrowserScreen} options={{headerShown:true}} /> </Stack.Navigator> </NavigationContainer> </Provider> ); } }
2. สร้างไฟล์ RootNavigation.js
RootNavigation.js
import * as React from 'react'; export const navigationRef = React.createRef(); export function navigate(name, params) { navigationRef.current?.navigate(name, params); } export function reset() { navigationRef.current?.reset(); } export function pop() { navigationRef.current?.pop(); } export function goBack() { navigationRef.current?.goBack(); } export function popToTop() { navigationRef.current?.popToTop(); }
3. เมื่อต้องการเปลี่ยนไปหน้าไหนให้ใช้คำสั่ง
ImageAlbum.js
import React, { Component } from 'react'; import { View } from 'react-native'; import * as RootNavigation from '../RootNavigation'; export default class ImageAlbum extends Component { constructor(props) { super(props); } next = () => { RootNavigation.navigate('Login'); } openImageBrowser = () => { RootNavigation.navigate('ImageBrowser', { pdata: this.props.pdata }); } render(){ return( <View> <Button title="click" onPress={()=>this.openImageBrowser}></Button> <Button title="next" onPress={()=>this.next}></Button> </View> ); } }