使导航对 React Native 应用程序中的所有组件可用

Making navigation available to all components in React Native app

我在我的 React Native 应用程序中使用 React Navigation 5,但我不太清楚如何让所有组件都可以使用导航。我还想提及我的应用程序使用 Redux 进行状态管理,但我没有将 React NavigationRedux 集成——也许我应该这样做!

我的 App.js 呈现我的 Navigator.js 组件,如下所示。顺便说一句,我的应用程序需要身份验证,导航器功能的关键功能之一是将未经身份验证的用户重定向到登录屏幕。

class Navigator extends Component {

   render() {
        return (
            <NavigationContainer>
                {
                   this.props.isAuthenticated
                   ? <MainMenuDrawer.Navigator drawerContent={(navigation) => <DrawerContent member={this.props.member} navigation={navigation} drawerActions={DrawerActions} handleClickLogOut={this.handleClickLogOut} />}>
                       <MainMenuDrawer.Screen name="Home" component={HomeStack} />
                       <MainMenuDrawer.Screen name="ToDoList" component={ToDoListStack} />
                     </MainMenuDrawer.Navigator>
                   : <SignInStack />
                }
            </NavigationContainer>
        );
      }
}

然后在我的 HomeStack 中,我有我的 Dashboard 组件,它恰好是一个需要访问 navigation 的 class 组件。这是我的 HomeStack:

const HomeStackNav = new createStackNavigator();

const HomeStack = () => {

   return(
      <HomeStackNav.Navigator screenOptions={{ headerShown: false }}>
         <HomeStackNav.Screen name="DashboardScreen" component={Dashboard} />
         <HomeStackNav.Screen name="SomeOtherScreen" component={SomeOtherComponent} />
      </HomeStackNav.Navigator>
   );
}

export default HomeStack;

说,我的 Dashboard 组件如下所示。如何使 navigation 可用于此组件?

class Dashboard extends Component {

   handleNav() {

      // Need to use navigation here...
   }

   render() {
      return (
         <Text>Welcome to Dashboard</Text>
         <Button onPress={() => this.handleNav()}>Go somewhere</Button>
      );
   }
}

function mapStateToProps(state) {
    return {
        member: state.app.member
    };
}

function mapDispatchToProps(dispatch) {

    return {
        actions: bindActionCreators(appActions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);

是否需要手动将 navigation 传递给每个组件?这似乎过于重复并且容易出错。如何让 navigation 在我的整个应用程序中可用?

解决方案 1:

你可以使用 useNavigation 挂钩功能组件

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


const navigation = useNavigation();

navigation.navigate("interests");
//or
navigation.push("interests");

解决方案 2:

您可以使用 HOC withNavigation 在 class 组件 Ref

的任何组件中导航道具

您可以通过

安装@react-navigation/compat
yarn add @react-navigation/compat

您可以像下面这样导入

import { withNavigation } from '@react-navigation/compat';

你可以像下面那样使用withNavigation

export default withNavigation(Dashboard)

注意:那么你可以在Dashboard组件

中使用this.props.navigation