this.props.navigation 在使用 DrawerNavigator 时未定义

this.props.navigation is undefined when using DrawerNavigator

我正在将 'react-navigation' 的 DrawerNavigator 作为 this 文档集成到我的项目中。但是当我 运行 项目时,它总是在单击按钮时出现此错误:

TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate')

当我从左向右滑动时,没有任何反应,没有打开抽屉。

我已经检查过 this.props,它在控制台中总是记录为空 {}。 我尝试了很多解决方案,但仍然没有用。

calculator.js

export default class Calculator extends Component {
    constructor(props) {
        super(props);
    }

    static navigationOptions = {
        drawerLabel: 'Calculator',
        drawerIcon: ({ tintColor }) => (
            <Image
                source={require('./../../res/images/icon_calculator.png')}
                style={[styles.icon, {tintColor: tintColor}]}
            />
        ),
    };

    render() {
        return (
            <View style={styles.container}>
                <View>
                    <Text style={styles.title}>Tip Calculator</Text>
                </View>
                <Button
                    onPress={() => this.props.navigation.navigate("SettingsScreen")}
                    title="Go to settings"
                />
            </View>
        );
    }
}

module.exports = Calculator;

settings.js

export default class Settings extends Component {
    constructor(props) {
        super(props);
    }

    static navigationOptions = {
        drawerLabel: 'Settings',
        drawerIcon: ({ tintColor }) => (
            <Image
                source={require('./../../res/images/icon_settings.png')}
                style={[styles.icon, {tintColor: tintColor}]}
            />
        ),
    };

    render() {
        return (
            <View style={styles.container}>
                <Text>Settings</Text>
                <Button
                    onPress={() => this.props.navigation.goBack()}
                    title="Go back home"
                />
            </View>
        );
    }
}

module.exports = Settings;

navigation.js

import {
    DrawerNavigator
} from 'react-navigation';
import Calculator from './../components/calculator/calculator.js';
import Settings from './../components/settings/settings.js';


const RootDrawer = DrawerNavigator({
    CalculatorScreen: {
        path: '/',
        screen: Calculator
    },
    SettingsScreen: {
        path: '/sent',
        screen: Settings
    }
}, {
    initialRouteName: 'CalculatorScreen',
    drawerPosition: 'left'
});

export default RootDrawer;

App.js

export default class App extends Component<{}> {
  render() {
    return (
      <Calculator/>
    );
  }
}

index.js

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('rn_tip_calculator', () => App);

我必须将 StackNavigatorDrawerNavigator 一起使用,还是我在配置中遗漏了什么?

完整源码,只是一个简单的示例工程,请看:https://github.com/HCMUS-IceTeaViet-SE/rn_tip_calculator

如有任何帮助,我们将不胜感激。谢谢!

你可以使用 dispatch api https://reactnavigation.org/docs/navigators/navigation-actions

1) 导入导航操作

import { NavigationActions } from 'react-navigation'

2) 调度导航操作:

const navigateAction = NavigationActions.navigate({
    routeName: 'SettingsScreen',
    params: {},
})

this.props.navigation.dispatch(navigateAction)

我是 React-Native 的新手,但有时我也会遇到这种情况。

我正在使用 Redux 和堆栈导航器....但这是我的工作示例...

import { StackNavigator } from 'react-navigation'
import { Animated, Easing } from 'react-native'
import LoginScreen from '../Containers/LoginScreen'
import LaunchScreen from '../Containers/LaunchScreen'
import HomeScreen from '../Containers/HomeScreen'
import SignUpScreen from '../Containers/SignUpScreen'
import SettingsScreen from '../Containers/SettingsScreen'
import VehicleCreateScreen from '../Containers/VehicleCreateScreen'
import styles from './Styles/NavigationStyles'

// Manifest of possible screens
const PrimaryNav = StackNavigator({
  LoginScreen: { screen: LoginScreen },
  LaunchScreen: { screen: LaunchScreen },
  HomeScreen: { screen: HomeScreen },
  SignUpScreen: { screen: SignUpScreen },
  SettingsScreen: { screen: SettingsScreen },
  VehicleCreateScreen: { screen: VehicleCreateScreen }
}, {
    // Default config for all screens
    headerMode: 'none',
    initialRouteName: 'LaunchScreen',
    navigationOptions: {
      headerStyle: styles.header
    },
    transitionSpec: {
      duration: 0,
      timing: Animated.timing,
      easing: Easing.step0,
    },
  },


)

export default PrimaryNav

然后从未连接到 REDUX 的组件

import React, { Component } from 'react';
import { Container, Content, List, ListItem, Icon, Text, Button, Left, Right, Badge } from 'native-base';
import { Image } from 'react-native'
import styles from './Styles/SideBarStyle';
// import backgroundImage from '../Images/vw.jpg'

const backgroundImage = require("../Images/vw.jpg");
const drawerImage = require("../Images/dirtyHandsDark.jpg");


export default class SideBar extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        // *********** HERE WE DECLARE AN ARRAY TO RENDER LISTS FROM. THIS COULD ALSO BE LIST OF BIKES FROM STORE.. ***********
        const datas = [
            {
                name: "Home",
                route: "HomeScreen",
                icon: "settings",
                bg: "#C5F442",
            },
            {
                name: "Repair",
                route: "HomeScreen",
                icon: "settings",
                bg: "#C5F442",
            },
            {
                name: "My Profile",
                route: "SettingsScreen",
                icon: "settings",
                bg: "#C5F442",
            },

        ];


        return (
            <Container>
                <Content bounces={false} style={{ flex: 1, backgroundColor: "#fff", top: -1 }}>
                    <Image source={backgroundImage} style={styles.drawerCover}>
                        <Image square style={styles.drawerImage} source={drawerImage} />
                    </Image>
                    <List
                        dataArray={datas}
                        renderRow={data =>
                            // *********** CREATE NEW LIST ITEM ON CLICK NAVIGATE TO APPROPRIATE LISTITEM.SCREEN ***********
                            <ListItem button noBorder onPress={() => this.props.navigation.navigate(data.route)}>
                                <Left>
                                    <Icon active name={data.icon} style={{ color: "#777", fontSize: 26, width: 30 }} />
                                    <Text style={styles.text}>
                                        {data.name}
                                    </Text>
                                </Left>
                                {data.types &&
                                    <Right style={{ flex: 1 }}>
                                        <Badge
                                            style={{
                                                borderRadius: 3,
                                                height: 25,
                                                width: 72,
                                                backgroundColor: data.bg,
                                            }}
                                        >
                                            <Text style={styles.badgeText}>{`${data.types} Types`}</Text>
                                        </Badge>
                                    </Right>}
                            </ListItem>}
                    />
                </Content>
            </Container>
        );
    }
}

你看我引用this.props.navigation.navigate没问题。 这是我的回购协议以供参考。 https://github.com/GavinThomas1192/motoMechanicMeeKanic/tree/master/App

发生这种情况是因为我没有 "connect" 我的 DrawerNavigator 到我的应用程序。

有两种方法可以实现:

  • 方式一:将DrawerNavigator注册为应用根组件。在 index.js 中更改:

    来自 AppRegistry.registerComponent('rn_tip_calculator', () => App);

    AppRegistry.registerComponent('rn_tip_calculator', () => RootDrawer);

    所以你可以删除 App.js 因为它现在没用了。

  • 第二种方式:保留注册App组件(在App.js中)作为应用根组件。然后把里面的 App 组件到 "connect" DrawerNavigator 到 app.

    export default class App extends Component<{}> {
      render() {
        return (
          <RootDrawer/>
        );
      }
    }
    

document 只字不提如何将导航器连接到应用程序,也只字不提注册组件或将导航器放入根组件中。像我这样的驱动新手疯了!