以下是我在 common.js 文件中定义的标头的代码:
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代码时,该应用程序运行平稳,没有任何错误。但是由于要在多个屏幕上使用Header,因此需要将其放在一个公共位置,以避免重复编码。
答案 0 :(得分: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