React Native多次使用父类中定义的组件

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

下面是我在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-native jsx
1个回答
2
投票

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

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

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

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);

文档是here

© www.soinside.com 2019 - 2024. All rights reserved.