react-native - 访问 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);
解决方案
看起来您的 HeaderComponent 可能不在导航堆栈中。
在这种情况下,您可以尝试以下解决方案:
首先导入withNavigation
您的文件,例如
import { withNavigation } from 'react-navigation';
之后将您的组件导出更改为
export default connect(
mapStateToProps,
mapDispatchToProps
)(withNavigation(ApplicationHeader));
因此,您将可以访问此组件中的导航专家。
您的 ApplicationHeader 也可以移动到内部容器组件。不必在 App.js 中使用导航道具。
希望这会帮助你。
推荐阅读
- android - 无法将 android 库上传到 JitPack.io。无法应用插件 [id 'com.android.internal.version-check']
- reactjs - React Native Community Picker 不显示任何内容并且不打开
- javascript - 填充数组中未定义的元素
- flutter - 在 FutureBuilder 中添加查询以仅为登录用户及其信息检索数据 Flutter
- python - CNN 中的 Conv2D 输出形状太小
- python - 当我在 VS Code 中运行 python 脚本时,我总是得到看起来是它用来执行脚本的命令的命令文本。我怎样才能摆脱它?
- javascript - 动态 CSS 内容性能
- reactjs - 正确键入作为道具传递的组件
- javascript - Nativescript Vue Timepicker 与 Vuex
- reactjs - 需要为 axios 创建一个通用函数 .then 和 catch