我遇到了一个错误,即“ undefine不是一个对象(评估'_this.props')。这是一个非常简单的代码,我正在使用react native的现代功能。在这里我没有使用class。
我的代码是这个App.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/>
);
}
和Route.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/>
);
}
还有Homescreen.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>
)
}
和DetailScreen.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>
)
}
答案 0 :(得分:0)
从react-navigation尝试withNavigation
,您会看到此错误,因为您没有从父级传递导航。
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>
)
})
答案 1 :(得分:0)
其解决方法
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'