从标题打开抽屉-React Navigation 5x

时间:2020-05-16 14:45:12

标签: react-native typeerror react-navigation-v5

我正在尝试通过“页眉”中的按钮打开抽屉。我将导航道具从StackNavigator组件传递到Header.js组件。 它可以正确渲染,并且屏幕本身没有错误。当我单击Header.js内的TouchableOpacity时出现问题, 它引发此错误。我无法弄清楚为什么在这种情况下导航将未定义

任何帮助将不胜感激。

下面是我使用的代码。它具有3个文件- Main.js,StackNavigator.js和Header.js

##StackNavigator.js
import React from 'react'
import { createStackNavigator } from '@react-navigation/stack'

import Feed from '../screens/Feed'
import Profile from '../screens/Profile'
import Header from '../screens/Header'



const Stack = createStackNavigator()

export default function StackNavigator() {
  return (
    <Stack.Navigator
      initialRouteName="Profile"
      headerMode="screen"
      screenOptions={{
        header: ({ scene, previous, navigation }) => (
          <Header scene={scene} previous={previous} navigation={navigation} />
        ),
      }}
    >
      <Stack.Screen name="Feed" component={Feed} options={{ headerTitle: 'Twitter' }} />
      <Stack.Screen name="Profile" component={Profile} options={{ headerTitle: 'Tweet' }} />
    </Stack.Navigator>
  )
}





# Header.js

export default function Header({ scene, previous, navigation }) {
  const { options } = scene.descriptor


  
  const title =
    options.headerTitle !== undefined
      ? options.headerTitle
      : options.title !== undefined
      ? options.title
      : scene.route.name

  return (
    <Appbar.Header theme={{ colors: { primary: theme.colors.surface } }}>
      {previous ? (
        <Appbar.BackAction onPress={navigation.pop} color={theme.colors.primary} />
      ) : (
        <TouchableOpacity
          onPress={() => {
            navigation.openDrawer()				///Problem is here			
          }}
        >
          <Avatar.Image
            size={40}
            source={{
              uri: 'https://xyz.zbc.png',
            }}
          />
        </TouchableOpacity>
      )}
      <Appbar.Content
        title={previous ? title : <MaterialCommunityIcons name="twitter" size={40} />}
      />
    </Appbar.Header>
  )
}


#Main.js

import * as React from 'react'

import { NavigationContainer } from '@react-navigation/native'
import DrawerNavigator from './navigations/DrawerNavigator'
import StackNavigator from './navigations/StackNavigator'

export default function Main() {
  return (
    <NavigationContainer>
      <StackNavigator>
        <DrawerNavigator></DrawerNavigator>
      </StackNavigator>
    </NavigationContainer>
  )
}

错误:这是我点击 TouchableOpacity

时遇到的错误
typeerror navigation.opendrawer is not a function 

1 个答案:

答案 0 :(得分:0)

您应该像这样将StackNavigator包装到DrawerNavigator中

return (
 <NavigationContainer>
   <DrawerNavigator>
    <StackNavigator/>
   </DrawerNavigator>
 </NavigationContainer>

您在 Main 函数

中将其包装错误