按钮 onPress 事件期间导航错误
2017-05-16
378
我之前见过这个问题,但是我在 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);
1个回答
由于您从
navigationOptions
获取导航对象,因此您应该能够在其上调用导航,而无需执行 this.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' })}
/>
)
};
};
Matt Aft
2017-05-16