首页 > 解决方案 > react-navigation 导航不是函数错误。- 类组件

问题描述

我正在使用 react native 类组件,并且正在使用 react-navigation 在应用程序中路由。该指南主要针对功能组件,我正在尝试使用类组件来实现它。但是当我试图从 reactnavigation 中获取它时,它总是会抛出导航不是函数或未定义的错误。如果这是一个已经被问到的问题,我很抱歉,因为我对这个反应原生很陌生。

类组件

import React from 'react';
import { useNavigation } from '@react-navigation/native';
import { Button, Divider, Layout, TopNavigation ,Card,Text} from '@ui-kitten/components';

class HomeScreen extends React.Component {

     navigateDetails(navigation)  {
         debugger
         navigation('Details');
    };

    constructor(props) {
        super(props);
        console.log(this.props);
        this.state = { hover: false };
    }

    render()  {
        const navigation = this.props;
        return(

            <Button onPress={this.navigateDetails}>OPEN DETAILS</Button>

        );
    }
}

export default function (props) {
    const navigation = useNavigation();
    return <HomeScreen {...props} navigation={navigation} />;
}

标签: reactjsreact-nativereact-navigationreact-native-navigationreact-component

解决方案


首先,你必须确保你的类组件中存在导航道具(在你的代码中它已经存在),第二件事是this.props.navigation一个对象,而不是一个拥有不同功能的函数,navigate, push所以你必须执行这些函数,这是我对您的代码所做的一些更改,我希望这对您有用。

   class HomeScreen extends React.Component { 

    constructor(props) {
        super(props);
        console.log(this.props);
        this.state = { hover: false };
       }
        navigateDetails()  {
         this.props.navigation.navigate('Details');
       };

    render()  {
        const navigation = this.props;
        return(

            <Button onPress={()=>this.navigateDetails()}>OPEN DETAILS</Button>

        );
    }
}

export default function (props) {
    const navigation = useNavigation();
    return <HomeScreen {...props} navigation={navigation} />;
}

推荐阅读