[英]undefined is not an object (evaluating this.props.navigation.navigate) for onPress
I'm new to react native and getting this error:我是本机反应的新手并收到此错误:
undefined is not an object (evaluating this.props.navigation.navigate)
undefined 不是 object(评估 this.props.navigation.navigate)
This is a very common error, but the cause can be different as I'm unable to fix it by seeing other answers to similar questions.这是一个非常常见的错误,但原因可能不同,因为我无法通过查看类似问题的其他答案来修复它。
I have a screen that has this code:我有一个包含以下代码的屏幕:
function MyClientsScreen(props) {
return (
<Stack.Navigator>
<Stack.Screen name='Clients' component={ClientSrc} options={{
title: 'My Clients',
headerRight: () => (
<TouchableOpacity onPress={() => props.navigation.navigate('AddClients')}>
<Image source={require('../assets/addClient.png')} style={styles.addBtnImg} />
</TouchableOpacity>
),
}} />
<Stack.Screen name='AddClients' component={AddClientSrc} options={{
title: 'Add New Client',
headerRight: () => (
<TouchableOpacity>
<Text style={styles.headerButtton}>Save</Text>
</TouchableOpacity>
)
}} />
</Stack.Navigator>
);
}
The headerRight
button on the current screen should navigate to AddClients
(which is inside the stack navigation) when pessed.当前屏幕上的
headerRight
按钮应导航到AddClients
(位于堆栈导航内)。
navigation
is not defined anywhere and I was able to do it when I had the button code inside a function that I made const ClientSrc = ({ navigation }) => {...
but when I moved the button as a headerRight
button, the onPress
started throwing the error. navigation
没有在任何地方定义,当我在 function 中有按钮代码时,我能够做到这一点,我做了const ClientSrc = ({ navigation }) => {...
但是当我将按钮作为headerRight
按钮移动时, onPress
开始抛出错误。
In order to get a navigation prop that component should be part of navigation.为了获得导航道具,该组件应该是导航的一部分。
You can handle this differently like below你可以像下面这样不同地处理这个
<Stack.Screen name='Clients' component={ClientSrc} options={({ navigation }) => ({
title: 'My Clients',
headerRight: () => (
<TouchableOpacity onPress={() => navigation.navigate('AddClients')}>
<Image source={require('../assets/addClient.png')} style={styles.addBtnImg} />
</TouchableOpacity>
),
})} />
The options passes navigation to the function that is given you can use that and get access to navigation.这些选项将导航传递给 function,您可以使用它并访问导航。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.