在 StackScreen header 选项中设置 TouchableOpacity 时如何解决 navigation.navigate 错误?

How to solve navigation.navigate error when set TouchableOpacity in StackScreen header options?

我想在堆栈 header(右侧)上添加一个按钮(图标)。 On-click 它转到该页面,但它不工作。看起来“未定义不是 object(正在评估 'navigation.navigate')”。

下面是我的代码:

<Stack.Navigator>
  <Stack.Screen name="Page1" component={Page1} />
  <Stack.Screen
    name="Page2"
    component={Page2}
    options={{
      headerRight: () => (
        <View>
          <TouchableOpacity
            onPress={() => navigation.navigate('Page3')}>
            <Image source={require('../assets/image.png')} />
          </TouchableOpacity>
        </View>
      )
    }}
  />
  <Stack.Screen name="Page4" component={Page4} />
  <Stack.Screen name="Page5" component={Page5} />
</Stack.Navigator>

Navigation 仅在屏幕组件中定义。在您的情况下,您可以尝试 useNavigation 钩子导航到不同的屏幕。像这样导入:

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

并声明如下:

const navigation = useNavigation();

然后你将它添加到你的 TouchableOpacity 道具中,例如 onPress={() => navigation.navigate('Page3')}

希望这对你有用。谢谢

您可以将导航从选项传递到标题右:

options={({navigation}) => ({
         headerRight: () => (
          ...
         ),
      })}

或使用导航():

const navigation = useNavigation();

编辑 2:

修正了你的点心代码并且它工作正常: 您必须添加一个名为 'MyorderStack' 的 stackScreen,因为您正试图导航到那个。

<NavigationContainer independent={true}>
  <Stack.Navigator screenOptions={{ headerTintColor: 'blue' }}>
    <Stack.Screen name="Global Page" component={AppNavigator} options={{ headerShown: false }} />
    <Stack.Screen name="DetailOne" component={DetailOne} options={({navigation}) => ({ headerBackTitleVisible: false, title: 'Global Page',
      headerRight: () => (
        <View style={{flexDirection: 'row',justifyContent: 'flex-end',width: '50%'}}>
          <View style={{ marginRight: 10 }}>
            <TouchableOpacity onPress={() => navigation.navigate('MyorderStack')}>
              <Image source={require('./assets/shop.png')} style={styles.Image} />
            </TouchableOpacity>
          </View>
        </View>
       ), headerTitleAlign:'center', headerTintColor:colors.primary
      })}
    />
    <Stack.Screen name="DetailTwo" component={DetailTwo} options={{headerBackTitleVisible: false, headerTitleAlign: 'center', title: 'Global Page', headerTintColor: colors.primary}} />
    <Stack.Screen name="MyorderStack" component={MyorderStack} options={{headerBackTitleVisible: false, headerTitleAlign: 'center', title: 'Global Page', headerTintColor: colors.primary}} />
  </Stack.Navigator>
</NavigationContainer>