![](/img/trans.png)
[英]How to fix navigation problem in React Native (TypeError: undefined is not an object (evaluating '_this.props.navigation)
[英]TypeError: undefined is not an object (evaluating '_this.props.navigation') in React Native
我想工作,使用导航外部按钮组件,使造型更容易反应,但它给我的TypeError: undefined is not an object (evaluating '_this.props.navigation')
错误,当我尝试通过导航。 如果我在主屏幕上创建按钮,它工作正常,但这会使我的 HomeScreen 的样式表变得混乱,这意味着当我在其他地方使用该按钮时,我必须重复代码。
我在 App.js 中设置了堆栈导航,同样,当我不尝试将导航作为道具传递时,它可以正常工作。
这是HomeScreen.js
import React from "react";
import {
ScrollView,
StyleSheet,
Text,
View,
AsyncStorage,
} from 'react-native';
import Heading from '../heading';
import Input from '../Input';
import Button from "../Button";
export const Home = ({navigation}) => (
<View style={styles.container}>
<ScrollView style={styles.content}>
<Heading />
</ScrollView>
<Button/>
</View>
)
这是我的Button.js
/* eslint-disable prettier/prettier */
import React from 'react';
import {
StyleSheet,
Text,
View,
TouchableHighlight
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
function Button(){
const navigation = useNavigation()
return(
<View style={styles.buttonContainer}>
<TouchableHighlight
underlayColor='rgba(175, 47, 47, .75)'
activeOpacity={1.0}
style={styles.button}
onPress={() => {
navigation.navigate("New Medication");
}}>
<Text style={styles.submit}>
+
</Text>
</TouchableHighlight>
</View>
)
}
据我了解,这应该可以正常工作,那么为什么说它被传递为未定义?
更新:多亏了一些建议,我现在有了它,它不会出错,什么也不做。
这是我的App.js ,带有我的导航
const Stack = createStackNavigator();
function MyStack() {
return (
<Stack.Navigator
screenOptions={{
headerShown: false
}}>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="NewMedication" component={newMedScreen} />
</Stack.Navigator>
);
}
class App extends Component{
render(){
return(
<NavigationContainer>
<MyStack />
</NavigationContainer>
);
}
}
export default App;
我建议您创建一个带有屏幕名称的 const 并在任何地方重用它以避免此类问题。 你像这样<Stack.Screen name="NewMedication" component={newMedScreen} />
导航<Stack.Screen name="NewMedication" component={newMedScreen} />
,但尝试导航navigation.navigate("New Medication")
。当然这个屏幕不存在
const NEW_MEDICATION_SCREEN = 'NewMedication'
<Stack.Screen name={NEW_MEDICATION_SCREEN} component={newMedScreen} />
.....
onPress={() => navigation.navigate(NEW_MEDICATION_SCREEN)}>
为了使 Button 可重复使用,像这样使用它
function Button({onPress}){
return(
<View style={styles.buttonContainer}>
<TouchableHighlight
underlayColor='rgba(175, 47, 47, .75)'
activeOpacity={1.0}
style={styles.button}
onPress={onPress}>
<Text style={styles.submit}>
+
</Text>
</TouchableHighlight>
</View>
)}
export const Home = ({navigation}) => (
<View style={styles.container}>
<ScrollView style={styles.content}>
<Heading />
</ScrollView>
<Button onPress={() => navigation.navigate(NEW_MEDICATION_SCREEN)}/>
</View>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.