TypeError: Cannot read property 'navigate' of undefined React Native

Есть Stack Navigator в MainStack.js:

import React from 'react'
import { createStackNavigator } from '@react-navigation/stack';

import Main from './Main'
import ScannerMarker from './ScannerMarker';

const Stack = createStackNavigator();

export default function MainStack() {
    return(
        <Stack.Navigator initialRouteName='Main' screenOptions={{headerShown: false}}>
            <Stack.Screen name='Main' component={Main} />
            <Stack.Screen name='ScannerMarker' component={ScannerMarker} />
        </Stack.Navigator>
    );
}

И ScannerMarker.js:

import React from 'react';
import { StyleSheet, View, Text, Dimensions, Pressable } from 'react-native';
import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import Feather from 'react-native-vector-icons/Feather';
import Octicon from 'react-native-vector-icons/Octicons'

import Main from './Main';

export default function ScannerMarker({ navigation, setModalVisible }) {
    return (
        <View style={styles.markerContainer}>
            <View style={styles.topContainer}>
                <View style={styles.topBar}>
                    <MaterialIcon name="support-agent" size={32} color="#fffeef" backgroundColor={'none'} onPress={() => navigation.navigate(Main)} />
                    <Feather name="x" size={32} color="#fffeef" backgroundColor={'none'} onPress={() => navigation.goBack(Support)}/>
                </View>
                <Text style={styles.topText}>Point scanner to{'\n'}vending qr-code</Text>
            </View>
            <View style={styles.middleContainer}>
                <View style={styles.leftContainer}></View>
                <View style={styles.scannerSquare}></View>
                <View style={styles.rightContainer}></View>
            </View>
            <View style={styles.bottomContainer}>
                <Pressable style={styles.button} onPress={() => setModalVisible(false)}>
                    <Octicon name="number" size={20} color="#fffeef" style={styles.chargerIcon}/>
                    <Text style={styles.buttonText}>  Enter vending{'\n'}number</Text>
                </Pressable>
            </View>
        </View>
    )
}

ScannerMarker в свою очередь является частью Scanner() в Scanner.js:

import React from 'react';
import { StyleSheet, Linking, Dimensions} from 'react-native';
import QRCodeScanner from 'react-native-qrcode-scanner';
import { RNCamera } from 'react-native-camera';

import ScannerMarker from './ScannerMarker';

export default function Scanner({ modalVisible, setModalVisible }) {
    onSuccess = e => {
      Linking.openURL(e.data)
      setModalVisible(!modalVisible)
    };
  
    return (
        <QRCodeScanner
            onRead={this.onSuccess}
            flashMode={RNCamera.Constants.FlashMode.auto}
            cameraStyle={styles.cameraStyle}
            showMarker={true}
            customMarker={
                <ScannerMarker setModalVisible={setModalVisible}> </ScannerMarker>
            }
        />
    );
}

При нажатии на иконки "onPress={() => navigation.navigate(...)}" или onPress={() => navigation.goBack()} получаю ошибки:

TypeError: Cannot read property 'navigate' of undefined

и

TypeError: Cannot read property 'goBack' of undefined

Не понимаю в чём проблема. параметр navigation передан в компонент ScannerMarker, а все компоненты объявлены в Stack Navigator внутри MainStack.js.

Всё завёрнуто в NavigationContainer в App.js:

import * as React from 'react';
import { NavigationContainer} from '@react-navigation/native';

import MyDrawer from './components/Drawer'

export default function App() {
  return (
    <NavigationContainer>
      <MyDrawer />
    </NavigationContainer>
  );
}

Ответы (1 шт):

Автор решения: ReinRaus

Для использования navigation в любом компоненте необходимо воспользоваться функцией useNavigation:

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

export default function MyComp() {
    const navigation = useNavigation();
    return (
        <View>
            <Button
                title="Go to Home"
                onPress={() => navigation.navigate('Home')}
            />
        </View>
    );
};

Другой вариант решения данной задачи передать navigation компоненту MyComp через props:

export default function MyComp( {navigation} ) {
    //...
};

<MyComp navigation={props.navigation} />

Источник:
https://reactnavigation.org/docs/connecting-navigation-prop

P.S. Ваш код содержит потенциальную проблему иного характера:
Вы делаете делаете navigate(Main) , а должны navigate('Main').
В первом случае Main - это конкретный компонент, а во втором - имя экрана в стэке навигации.

→ Ссылка