【问题标题】:I keep getting errors that "navigation" is not defined我不断收到未定义“导航”的错误
【发布时间】:2020-07-22 17:46:52
【问题描述】:

我正在尝试创建一个导航到另一个页面的登录按钮,但我不断收到未定义“导航”的错误

这是错误的屏幕截图: screenshot here

screenshot here 这就是应用组件:

export default function App({navigation}) {
  const { navigate } = this.props.navigation;
  return (
    
    <View style={styles.container}>
     
     <Image
        
        source={logo}
        style={styles.stretch}
      />
      <Image
        
        source={logo2}
        style={styles.stretch2}
      />
      
  
  <Button title="Login" style={[styles.buttonContainer, styles.loginButton,styles.top]} onPress={() => navigation.navigate("Details")} >
     <Text style={styles.loginText}>LOG IN</Text>
   </Button>  
   <TouchableHighlight style={[styles.buttonContainer2, styles.loginButton2,styles.top2]} >
     <Text style={styles.loginText2}>Register</Text>
   </TouchableHighlight>  
        <NavigationContainer>
          
  <Stack.Navigator >
  <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={Details} />
        </Stack.Navigator>
        
</NavigationContainer>
        </View>
    
  );
}

在这里我在使用导航 Ref 方法后卡住了: link here

【问题讨论】:

    标签: react-native expo stack-navigator


    【解决方案1】:

    函数组件中没有this.props

    export default function App({navigation}) {
      const { navigate } = this.props.navigation;
    

    这应该是

    export default function App({navigation}) {
      const { navigate } = navigation;
    

    请注意,您已经从函数签名中的 props 中解构了导航

    【讨论】:

    • 现在将在帖子中附上屏幕截图
    【解决方案2】:
    1. 您的 App 组件是一个 React 钩子,因此调用 this.props 将不起作用。您可以在应用的参数中使用navigation

    2. 导航道具仅适用于包装在 &lt;NavigationContainer&gt; 组件中的组件。尝试从 App 组件调用 navigate 时,您可能仍然会遇到错误,因为 &lt;NavigationContainer&gt; 是它的子组件。

    您最好的选择是仅在 &lt;NavigationContainer&gt; 内的组件上使用 navigation 属性,或者根据文档像这样访问它:

    https://reactnavigation.org/docs/navigating-without-navigation-prop

    编辑: 如果你想在导航容器之外访问导航,你需要一个指向它的 ref。

    import React, { useRef } from "react";
    
    export default function App({}) {
        const navigationRef = useRef(null)
    
        // Then wherever you wanna call navigate you do this:
        // () => navigationRef.current.navigate("Details")
        // make sure you do a null check on navigationRef.current if you want to be extra safe
    
        return (
            <NavigationContainer ref={navigationRef}>
            ....
            </NavigationContainer>
        )
    }
    

    【讨论】:

    • 我已经试过了,结果第二张截图出错了
    • 是的,结帐点 2。当提供该道具的 NavigationContainer 是它的子组件时,您正在从 App 组件访问导航。
    • 如果你console.log App的navigation prop,你会看到它是未定义的。
    • 如果我想添加导航,我该怎么办?
    • 更新答案,一秒
    猜你喜欢
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多