javascript - typeError:无法读取未定义的属性“goBack”
问题描述
所以场景是,我想在我的应用程序顶部实现一个 GoBack 图标,它可以返回上一页。我正在使用堆栈导航器并禁用标题。所以我需要一个返回按钮。我决定为此制作一个组件,这是我的代码,
import { Ionicons } from '@expo/vector-icons';
function GoBack(){
return (
<Ionicons onPress={()=>this.props.navigation.goBack()} name="md-arrow-back" size={24} color="#0c85f3" />
);
}
export default GoBack;
如果我这样做,那么它会向我显示 typeError: Cannt read property 'goBack' of undefined. 但是如果我将 onPress 作为道具并实现相同的代码行,onPress={()=>this.props.navigation.goBack()}
它会完美运行。
我不能到处应用 onPress 道具。它是一个有很多屏幕的应用程序。我如何将它应用到组件本身?我认为我对 React 导航缺乏深入的了解。请帮助我理解解决方案。
这是我使用 GoBack 组件的方式:
import React, { Component } from 'react';
import {View, StyleSheet, Text, FlatList} from 'react-native';
import TestRoomtData from '../../../testData';
import HistoryCard from '../../../components/cards/historyUserCard';
import GoBack from '../../../shared/goBackButton';
class UserHistory extends Component{
render(){
return(
<View style={styles.container}>
<View style={{flexDirection:"row",}}>
<GoBack />
<Text style={styles.title}>History</Text>
</View>
<Text style={styles.title01}>Past Patients</Text>
<FlatList
data={TestRoomtData}
renderItem={({item})=>([
<View>
<HistoryCard
prescription={item.prescription}
diagnosis={item.diagnosis}
date={item.date}
source={{
uri: item.uri
}}
btnText01="More"
btnText02="Edit"
onPressBtn2={()=> this.props.navigation.navigate('Edit History') }/>
</View>
]
)}
/>
</View>
);
}
}
解决方案
在 react 的功能组件中,不能使用this
关键字来访问 props。在当前情况下,您必须以这样的方式传递导航道具GoBack
,
function Goback(props) {
const { navigation } = props;
return (
<Ionicons
onPress={() => navigation.goBack()}
name="md-arrow-back"
size={24}
color="#0c85f3"
/>
);
}
现在,调用 GoBack 组件,
<GoBack
navigation={{ goBack: () => goBack() }}
/>
推荐阅读
- domain-driven-design - 订单和库存 DDD - 应该在哪里处理分配/预订?
- c# - 使用 TrackBar 播放音乐时断断续续
- python - 我从 Python 中的 Tkinter 收到的奇怪错误
- sql - 在更新之前通过修改数据从另外两个更新主表
- java - 为下拉菜单创建 Angular 服务
- nativescript - 如何使用 NativeScript 切换 UITabBar 半透明属性?
- mongodb - MongoDB:按索引删除数组元素,操作顺序?
- javascript - 汇总具有相同属性名称的对象的值
- c# - 如何测试类型是否可实例化?
- ios - 如何在 iOS 应用程序中有效地实现跳过逻辑分支?