未定义不是对象(评估'this.props.navigation.navigate') - 抽屉导航器

问题描述 投票:0回答:1

我收到了 - undefined不是一个对象(评估'this.props.navigation.navigate')。我知道已经有一些关于这个问题的答案,但我没有找到任何抽奖导航器,我发现只有Stack Navigator。 (我正在使用react-navigation V3)所以这是我的DrawerNavigator.js:

import React from 'react';
import { Platform, Dimensions, Button, View, Text } from 'react-native';
import { createDrawerNavigator, createAppContainer, StackNavigator, withNavigation } from 'react-navigation';
import {Header} from 'react-native-elements';
import Hamburger from 'react-native-animated-hamburger';

class MenuButton1 extends React.Component {
  constructor(props)
  {
      super(props);
      this.state = {
        active: false,
      }

  }
  render () {
    const { navigate } = this.props.navigation;
      return (
          <React.Fragment>   
          <Hamburger active={this.state.active}
     type="cross"
     onPress={() => this.setState({active: !this.state.active}) || navigate('DrawerOpen')} 
     />   
          </React.Fragment>
      )
  }
}


class HomeScreen extends React.Component {
    render() {
      return (
        <React.Fragment>
          <Header
          leftComponent={<MenuButton1 />}
          />

        <View style={{top: 30 }}>
            <Text> Hello </Text>
        </View>
        </React.Fragment>
      );
    }
  }



const WIDTF = Dimensions.get('window').width;

const DrawerConfig = {
    drawerWidth: WIDTF*0.80,
    draertType: 'slide'    
}

const DrawerNavigator = createDrawerNavigator ({
    HomeScreen: {
      screen: HomeScreen,

    }
},
  DrawerConfig
);


export default createAppContainer (DrawerNavigator);

还有我的App.js:

import React, {Component} from 'react';
import DrawerNavigator from './components/DrawerNavigator';

export default class App extends React.Component {
  render() {
    return (
      <React.Fragment>
      <DrawerNavigator />
      </React.Fragment>
    );
  }
}

问题是:

enter image description here

react-native react-navigation
1个回答
0
投票

导航对象仅适用于抽屉导航器的直接子画面

您可以使用MenuButton1包装withNavigation以访问导航对象...或者只是将导航逻辑包装在一个方法中并将其作为道具传递给您的MenuButton,如:

class MenuButton1 extends React.Component {
  constructor(props) {
    // ...
  }

  render() {
    const { onDrawerOpen } = this.props;
    return (
      <React.Fragment>
        <Hamburger
          active={this.state.active}
          type="cross"
          onPress={() => this.setState({ active: !this.state.active }) || onDrawerOpen()
          }
        />
      </React.Fragment>
    );
  }
}

-

class HomeScreen extends React.Component {
  render() {
    return (
      <React.Fragment>
        <Header
          leftComponent={(
            <MenuButton1
              onDrawerOpen={() => this.props.navigation.openDrawer()}
            />
)}
        />

        <View style={{ top: 30 }}>
          <Text> Hello </Text>
        </View>
      </React.Fragment>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.