我不能在5版中使用this.props.navigation.navigate。

问题描述 投票:1回答:1
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 (评价'_this.props.navigation.openDrawer()')

reactjs react-native react-navigation react-navigation-v5
1个回答
1
投票

由于你使用的是v5,你可以从@react-navigationnative中使用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>

希望这能帮到你!

© www.soinside.com 2019 - 2024. All rights reserved.