首页 > 解决方案 > React Native 多次使用父类中定义的组件

问题描述

下面是我在common.js文件中定义的 Header 的代码:

class HeaderStyle extends Component {
    render() {
        return (
            <Header style={{ elevation: 5 }}>
                <Left style={{ flex: 1 }}>
                    <Icon name="md-menu" size={30} onPress={() => this.props.navigation.openDrawer()} />
                </Left>
                <Body style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                    <Image style={{ width: 80, height: 45, }} source={require('./resources/hr-pro-logo.png')} />
                </Body>
                <Right style={{ flex: 1 }}>
                    <Icon name="md-search" size={30} onPress={() => alert('hi there')} />
                </Right>
            </Header>
        );
    }
}

这是我的DashboardScreen.js的代码:

export default class DashboardScreen extends Component {
    render() {
        return (
            <View style={{ flex: 1 }}>
                <HeaderStyle /> // This is where I'm using the Header imported from common.js
                <View>
                    <FlatList
                        // Code to populate my list
                    />
                </View>
            </View>
        );
    }

我已经能够在我的仪表板中导入标题,但是当我单击菜单图标onPress={() => this.props.navigation.openDrawer()}时,它会引发错误undefined is not an object (evaluating '_this.props.navigation.openDrawer')

如果有人可以帮助我解决此问题,我将不胜感激,我希望能够在单击菜单图标时打开抽屉。

仅供参考 - 当我直接在仪表板中使用标题代码时,应用程序运行顺利,没有错误。但是由于我想在多个屏幕上使用 Header,所以我需要将它保存在一个公共位置以避免重复编码。

标签: react-nativejsx

解决方案


您必须将navigation道具传递给您的组件:

<HeaderStyle navgation={this.props.navigation} />

或者,您可以使用withNavigationreact-navigation 中的函数:

import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';

class MyBackButton extends React.Component {
  render() {
    return (
    //you Header render
    );
  }
}

// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);

文档在这里


推荐阅读