简体   繁体   中英

How to export createStackNavigator as class in React Native?

I read here that using the the createStackNavigator as a Component class was possible, and I was trying to achieve that, but I always got an error.

Instead of this:

export default createStackNavigator({
    Messages
}, {
    defaultNavigationOptions: {
        gesturesEnabled: false
    }
})

I tried this:

class MessagesStack extends React.Component {
    render() {
        const RouteConfigs = {
            Messages
        };

        const NavigatorConfigs = {
            defaultNavigationOptions: {
                gesturesEnabled: false
            }
        };

        const Stack = createStackNavigator(RouteConfigs, NavigatorConfigs);
        return <Stack />;
    }
}

export default MessagesStack;

But I always get this error:

Invariant Violation: Invariant Violation: The navigation prop is missing for this navigator. In react-navigation 3 you must set up your app container directly. More info: https://reactnavigation.org/docs/en/app-containers.html

So, I tried to correct it, by adding the navigation prop, like so:

return <Stack navigation={this.props.navigation} />;

But then I got a new error

TypeError: TypeError: No "routes" found in navigation state. Did you try to pass the navigation prop of a React component to a Navigator child? See https://reactnavigation.org/docs/en/custom-navigators.html#navigator-navigation-prop

Is this possible? The main reason I want to do it, is to be able to @inject and use @observer for mobx stores. This way when I change de background color in the store, it will change on every stack that has the store injected and is observing.

EDIT

Where I'm calling MessagesStack from:

export default createBottomTabNavigator({
    DayStack: {
        screen: DayStack,
        navigationOptions: {...}
    }
    MessagesStack: {
        screen: MessagesStack,
        navigationOptions: {...}
    }
    ... OtherStacks here...
}, {
    initialRouteName: 'DayStack',
});

according to my understanding from the error I think the issue is not with your createStackNavigator the actual problem is that now from version 3 of react-navigation you have to manually pass the createStackNavigator into the createAppContainer so that the created Container can be the main component for React native to render

import { createAppContainer, createStackNavigator } from 'react-navigation';
// you can also import from @react-navigation/native

const AppNavigator = createStackNavigator(...);

// you have to pass the app navigator into app container like this
const AppContainer = createAppContainer(AppNavigator);

// Now AppContainer is the main component for React to render

export default AppContainer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM