反应本机导航取消定义对象错误



我遇到了一个名为"undefined不是对象(评估'_this.props'(的错误。这是一个非常简单的代码,我正在使用反应本机的现代函数。我在这里没有使用类。

我的代码是这个应用程序.js

import React from 'react';
import { StyleSheet, Text, View,TextInput,Button } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Routes from './Routes';

export default function App() {
return (
<Routes/>
);
}

和路线.js

import React from 'react';
import { StyleSheet, Text, View,TextInput,Button } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { render } from 'react-dom';
/// define all components here
import HomeScreen from './src/Component/HomeScreen';
import DetailScreen from './src/Component/DetailScreen';

// Routes defination
export default function Routes(){
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Details: DetailScreen,
},
{
initialRouteName: 'Home',
}
);
const AppContainer = createAppContainer(RootStack);
return(
<AppContainer/>
);
}

和主屏幕.js我需要从哪里跳转到详细信息屏幕

import React from 'react';
import { StyleSheet, Text, View,TextInput,Button } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
export default function HomeScreen() {
return (
<View>
<Text>I am testing from the home screen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}></Button>
</View>
)
}

和详细信息屏幕.js

import React from 'react';
import { StyleSheet, Text, View,TextInput,Button } from 'react-native';
export default function DetailScreen() {
return (
<View>
<Text>I am testing from the detail screen</Text>
</View>
)
}

尝试从 react-navigationwithNavigation,您会看到此错误,因为您没有从父级传递导航。

import React from 'react';
import { StyleSheet, Text, View,TextInput,Button } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import {withNavigation} from 'react-navigation'
export default withNavigation(function HomeScreen() {
return (
<View>
<Text>I am testing from the home screen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}></Button>
</View>
)
})

它的修复

export default function HomeScreen(props) {
return (
<View>
<Text>I am testing from the home screen</Text>
<Button
title="Go to Details"
onPress={() => props.navigation.navigate('Details')}></Button>
</View>
)
}

因为 this.props 只出现在类组件中,但在函数组件中它没有"this">

最新更新