首页 > 解决方案 > 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>





        );
    }
}

标签: javascriptreactjsreact-nativereact-routernavigation

解决方案


在 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() }}
/>

推荐阅读