React Native 如何在navigationcontainer外部访问导航

icomxhvb  于 2023-03-24  发布在  React
关注(0)|答案(1)|浏览(138)

这里我试图将导航添加到我的react-native项目中,按钮寄存器应该导航到成功页面组件,但唯一的问题是按钮寄存器存在于导航容器之外,这里我试图访问导航容器之外的“导航”这里是导航容器:

import * as React from 'react';
import { Text, View, StyleSheet,Image,TouchableHighlight,TextInput,
  Button, } from 'react-native';
import Constants from 'expo-constants';
import logo from './assets/logo4.png'
import logo2 from './assets/CFA_approved_prep_provider_RGB.png'
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { enableScreens } from 'react-native-screens';
import { Component } from 'react';
import * as Font from 'expo-font';
import  { useRef } from "react";
import logo3 from './assets/logo3.png'


 
enableScreens();
const Stack = createStackNavigator();

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm

import { Card } from 'react-native-paper';


    

export default function App() {
  const navigationRef = useRef(null)
  
  return (
    
    <View style={{flex: 1,
      justifyContent: 'center',
      
      backgroundColor:'white',}}>
     
     
      
  
  
        <NavigationContainer ref={navigationRef}>
          
  <Stack.Navigator initialRouteName="SplashScreen">
  <Stack.Screen name="SplashScreen" component={SplashScreen} /> 
  <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={Details} />
        <Stack.Screen name="SuccessPage" component={SuccessPage} />

        </Stack.Navigator>
        
</NavigationContainer>


  
        </View>

在这里,我尝试这样访问它:

<View style={[{ width: "90%", margin: 10 }]}>
   <Button
      onPress={() => navigationRef.current.navigate("SuccessPage")}
      title="Register"
      
    />
</View>

这就是错误:
screenshot here
你知道还能做什么吗

fv2wmkja

fv2wmkja1#

您可以在NavigationRef的帮助下从NavigationContainer外部访问导航。
添加导航容器参照

// App.js

import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';

export default function App() {
  return (
    <NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
  );
}

创建和使用导航参考。

// RootNavigation.js

import { createNavigationContainerRef } from '@react-navigation/native';

export const navigationRef = createNavigationContainerRef()

export function navigate(name, params) {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}

// add other navigation functions that you need and export them

相关问题