之前我曾见过这个问题,但我在Stack Overflow和其他地方找到的解决方案都没有帮助我。
单击“信息”按钮
时出现此错误undefined is not an object evaluating (_this.props.navigation)
我不知道为什么,但我知道它与ChatScreen类中的这一行有关:
const { navigate } = this.props.navigation;
我没有得到的是,同一行在HomeScreen类中工作正常。
所以我不确定如何解决它。
如果有人可以提供一些建议,我会非常感激。
谢谢!
这是我的代码:
import React from 'react';
import { AppRegistry, Text, View, Button,} from 'react-native';
import { StackNavigator } from 'react-navigation';
import { TabNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
//works
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={ () => navigate('Chat', { user: 'Abe'})}
title = "Chat with Abe"
/>
</View>
);
}
}
class ChatScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const { state, setParams } = navigation;
const isInfo = state.params.mode === 'info';
const {user} = state.params;
//throws the error: undefined is not an object evaluating this.props.navigation
const { navigate } = this.props.navigation;
return {
title: isInfo ? `${user}'s Contact Info:` : `Chat with ${state.params.user}`,
headerRight: (
<Button
title={ isInfo ? 'Done' : `${user}'s info` }
onPress={ () => navigate('Info', { user: 'Abe' })}
/>
)
};
};
}
class InfoScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const {user} = state.params;
};
render() {
return (
<View>
<Text>
{user}'s Info
</Text>
</View>
);
}
}
//navigation tabs
const MainScreenNavigator = TabNavigator({
Home: { screen: HomeScreen }
});
const NavTest = StackNavigator({
Home: { screen: MainScreenNavigator },
Chat: { screen: ChatScreen },
Info: { screen: InfoScreen }
});
//title
MainScreenNavigator.navigationOptions = {
title: 'My Chats',
}
AppRegistry.registerComponent('NavTest', () => NavTest);
答案 0 :(得分:1)
由于您从navigationOptions
获取导航对象,因此您应该能够在不需要执行此操作的情况下调用导航对象.props.navigation:
static navigationOptions = ({ navigation }) => {
const { state, setParams, navigate } = navigation;
const isInfo = state.params.mode === 'info';
const {user} = state.params;
return {
title: isInfo ? `${user}'s Contact Info:` : `Chat with ${state.params.user}`,
headerRight: (
<Button
title={ isInfo ? 'Done' : `${user}'s info` }
onPress={ () => navigate('Info', { user: 'Abe' })}
/>
)
};
};