首页 > 解决方案 > 访问 Header 组件上的 this.props.navigation

问题描述

我有一个 ApplicationHeader 组件,我想通过触摸导航到特定屏幕,但我得到了

undefined 不是对象(评估 this.props.navigation.navigate)

应用程序.js

render() {
  return (
    <SafeAreaView forceInset={{ bottom: 'never' }} style={styles.container}>
      {Platform.OS === 'ios' && <StatusBar barStyle="default" />}
      <Provider store={store}>
        <ApplicationHeader navigation={this.props.navigation} />
        <AppNavigator />
      </Provider>
    </SafeAreaView>
  );
}

ApplicationHeader.js

class ApplicationHeader extends Component {
  constructor(props) {
    super(props)
  }

  openWishlist() {
    this.props.navigation.navigate('Wishlist')
  }

  render() {
    const { isLogged } = this.props;
    return (
      <View style={AppStyle.header}>
        <TouchableOpacity onPress={() => this.openWishlist()}>
          {!isLogged && (<Image source={imgWishList} style={AppStyle.headerWishlist} />)}
          {isLogged && (<Image source={imgWishListLogged} style={AppStyle.headerWishlist} />)}
        </TouchableOpacity>
      </View>
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(ApplicationHeader);

标签: react-native

解决方案


看起来您的 HeaderComponent 可能不在导航堆栈中。

在这种情况下,您可以尝试以下解决方案:

首先导入withNavigation您的文件,例如

import { withNavigation } from 'react-navigation';

之后将您的组件导出更改为

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withNavigation(ApplicationHeader));

因此,您将可以访问此组件中的导航专家。

您的 ApplicationHeader 也可以移动到内部容器组件。不必在 App.js 中使用导航道具。

希望这会帮助你。


推荐阅读