[英]React-native: undefined is not an object (evaluating '_this3.props.navigation.navigate')
[英]react-native: undefined is not an object (evaluating '_this2.props.navigation') with react navigation
我剛剛開始在 React Native 中進行開發,但遇到了錯誤,我在我的應用程序中包含了抽屜導航,當它在內容視圖中被點擊時,側邊菜單欄會打開,但是當它被點擊時
<TouchableOpacity onPress={() =>this.props.navigation.toggleDrawer()}
style={{padding:10}}>
<Icon size={27} name='ios-menu' color='#fff' />
</TouchableOpacity>
它拋出一個錯誤。
undefined is not an object (evaluating '_this2.props.navigation')
下面是我的腳本
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, TouchableOpacity} from 'react-native';
import {Container,
Header,
Content,
List,
ListItem,
Left,
Icon,
Body,
Title,
Right} from 'native-base';
class HomeScreen extends Component{
static navigationOptions = {
title: 'Home',
headerStyle: {
backgroundColor: '#28608c',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
headerLeft:(
<TouchableOpacity onPress={() =>this.props.navigation.toggleDrawer()}
style={{padding:10}}>
<Icon size={27} name='ios-menu' color='#fff' />
</TouchableOpacity>
),
headerRight:(
<TouchableOpacity style={{padding:10}}>
<Icon size={27} name='search' color='#fff' />
</TouchableOpacity>
)
};
render() {
return (
<Container>
<Content contentContainerStyle={{
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}}>
<Text onPress={() =>this.props.navigation.toggleDrawer()}>HomeScreen</Text>
</Content>
</Container>
);
}
}
export default HomeScreen;
從反應導航文檔:
嘗試在
navigationOptions
使用this.props
可能很誘人,但由於它是組件的靜態屬性,因此this
不引用組件的實例,因此沒有可用的道具。 相反,如果我們使navigationOptions
成為一個函數,那么 React Navigation 將使用包含{ navigation, navigationOptions, screenProps }
的對象調用它
因此,您需要將navigationOptions
更改為如下所示:
static navigationOptions = ({ navigation }) => {
return {
// snip...
headerLeft:(
<TouchableOpacity onPress={() => navigation.toggleDrawer()} // remove "this.props" here
style={{padding:10}}>
<Icon size={27} name='ios-menu' color='#fff' />
</TouchableOpacity>
),
// snip...
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.