我正在尝试构建一个简单的嵌套导航器,即堆栈导航中的选项卡导航。当尝试通过下面的“myFunction”导航堆栈时,我得到“未定义不是对象 - 评估this.props.navigation”。我尝试了另一种方法,即通过导航选项的“headerright”实现堆栈导航 - 它可以工作。但我真的想通过内容部分的按钮实现它。代码如下,显示了两种导航方法:
从'react'导入React,{Component}; import { AppRegistry, 文本,视图,按钮,图像,StyleSheet 来自'react-native'; 从“react-navigation”导入{TabNavigator,StackNavigator};
class RecentChatsScreen extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: `Recent Chats`,
headerRight: <Button title="Go Chat" onPress={() => navigation.navigate('Chat', { user: 'Lucy' })}/>,
});
myFunction() {
const { navigate } = this.props.navigation;
navigate('Chat', { user: 'Lucy' });
}
render() {
return (
<View>
<Text>List of recent chats</Text>
<Button
onPress={
this.myFunction
}
title="Go Chat."
/>
</View>
);
}
}
class ChatScreen extends React.Component {
static navigationOptions = {
title: 'chat screen',
};
render() {
return <Text>Chat screen</Text>
}
}
class AllContactsScreen extends React.Component {
render() {
return <Text>List of all contacts</Text>
}
}
const MainScreenNavigator = TabNavigator({
Recent: { screen: RecentChatsScreen },
All: { screen: AllContactsScreen },
});
MainScreenNavigator.navigationOptions = {
title: 'My Chats',
};
const SimpleApp = StackNavigator({
Home: { screen: MainScreenNavigator },
Chat: { screen: ChatScreen },
});
AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
答案 0 :(得分:0)
你可能忘了绑定this
,所以当调用myFunction
时,它不在RecentChatsScreen
范围内。
尝试添加此
class RecentChatsScreen extends React.Component {
constructor(props) {
super(props);
this.myFunction = this.myFunction.bind(this);
}
}