首页 > 解决方案 > 我不能在版本 5 中使用 this.props.navigation.navigate

问题描述

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

import News from './src/screens/News';
import Photos from './src/screens/Photos'

const Drawer = createDrawerNavigator();

function App() {
  return (
    <NavigationContainer>
      <Drawer.Navigator initialRouteName="News" >
        <Drawer.Screen name="News" component={News}/>
        <Drawer.Screen name="Photos" component={Photos} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

export default App;

我尝试使用 this.props.navigation.openDrawer() 调用我的标题

<View style={style.iconHeader}>
  <TouchableOpacity onPress={() => this.props.navigation.openDrawer()}>
    <Feather name='menu' size={36} color='black' />
  </TouchableOpacity>
</View>

返回以下错误:TypeError: undefined is not an object (evalating '_this.props.navigation.openDrawer()')

标签: reactjsreact-nativereact-navigationreact-navigation-v5

解决方案


当您使用 v5 时,您可以使用来自 @react-navigation/native 的 DrawerActions

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

并这样做:

    const navigation = useNavigation();
      return (
      <View style={style.iconHeader}>
      <TouchableOpacity   onPress={() => {
          navigation.dispatch(DrawerActions.openDrawer());
        }}>
        <Feather name='menu' size={36} color='black' />
      </TouchableOpacity>
    </View>

希望这可以帮助!


推荐阅读