【问题标题】:React Native: Cannot read property 'navigation' of undefinedReact Native:无法读取未定义的属性“导航”
【发布时间】:2018-12-11 03:06:48
【问题描述】:

我正在尝试制作一个 onPress 功能,以便在单击菜单图标时,我的抽屉导航将打开。但是,我收到此错误:未处理的 JS 异常:无法读取未定义的属性“导航”。

这是我的 HeaderComponent.js 代码

import React from 'react';
import { StyleSheet } from 'react-native';
import { Header, Left, Icon, Body, Title, Right } from 'native-base';

const HeaderComponent = (props) => {
const { menuIconStyle } = styles;

return (
    <Header>
        <Left>
            <Icon
                style={menuIconStyle}
                name="menu"
                onPress={() => this.props.navigation.openDrawer()}
            />
        </Left>
        <Body>
            <Title>{props.headerText}</Title>
        </Body>
        <Right>

        </Right>
    </Header>
);
}

export default HeaderComponent;

const styles = StyleSheet.create({
menuIconStyle: {
    paddingLeft: 15,
},
});

希望有解决方案。谢谢!

【问题讨论】:

  • 似乎参数未定义。你如何渲染这个组件?
  • @nikosfotiadis 我将它导入 HomeScreen.js 并像这样呈现它
  • @user7381027 我假设HomeScreen 在道具中有navigation。如果是这种情况,您也需要将 navigation 传递给 HeaderComponent:&lt;HeaderComponent headerText={"Home"} navigation={this.props.navigation} /&gt;
  • @blaz 我明白了。它现在正在工作。谢谢!

标签: react-native react-navigation native-base


【解决方案1】:

您应该将导航道具从父级传递给子级,如下所示:

&lt;HeaderComponent navigation={this.props.navigation} /&gt;

然后你可以在你的子组件中使用导航

【讨论】:

    【解决方案2】:

    您的组件不是 ES6 类,而是一个函数。因此,您不能使用this.props,因为它不存在。

    onPress={() =&gt; props.navigation.openDrawer()}

    改用这个。

    【讨论】:

      猜你喜欢
      • 2018-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多