我有两个屏幕。每个屏幕包含三个子类。是的,我使用每个屏幕的tab.在我的第一个屏幕中,让我们说。Main-screen
有-> ScreenA, ScreenB, ScreenC
. 而我的 DetailScreen
有->。ScreenD, ScreenE, ScreenF
现在从我的 ScreenA
我有推去 ScreenD
. 代码在这里。
this.props.navigation.navigate('DetailScreen', {
onNavigateBack: this.refresh.bind(this)
})
refresh(commentText) {
alert('alert me')
}
在我的 ScreenD
我有一个按钮可以返回。并更新我的 ScreenA
:
this.props.navigation.state.params.onNavigateBack(this.state.commentText);
this.props.navigation.goBack();
但我总是得到错误,如 。
Undefined is not an object (evaluating 'this.props.navigation.state')
任何帮助将是巨大的。我的目标是更新我的 screen A
,当我从回来 screen D
我的主屏幕。
<ScreenA navigation={this.props.navigation} tabLabel= "ScreenA" props = {this.props} tabView={this.tabView}/>
<ScreenB navigation={this.props.navigation} tabLabel= "ScreenB" props = {this.props} tabView={this.tabView}/>
<ScreenC navigation={this.props.navigation} tabLabel= "ScreenC" props = {this.props} tabView={this.tabView} goToPage={ () => this.goToPage(2) }/>
详细屏幕。
<ScreenD navigation={this.props.navigation} tabLabel= "ScreenD" props = {this.props} tabView={this.tabView}/>
<ScreenE navigation={this.props.navigation} tabLabel= "ScreenE" props = {this.props} tabView={this.tabView}/>
<ScreenF navigation={this.props.navigation} tabLabel= "ScreenF” props = {this.props} tabView={this.tabView} goToPage={ () => this.goToPage(2) }/>
我的RootStackScreen 。
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import ScreenA from './ScreenA';
import ScreenB from './ScreenB';
const RootStack = createStackNavigator();
const RootStackScreen = ({navigation}) => (
<RootStack.Navigator headerMode='none'>
<RootStack.Screen name="ScreenA" component={ScreenA}/>
<RootStack.Screen name="ScreenB" component={ScreenB}/>
</RootStack.Navigator>
);
export default RootStackScreen;
1) 进入你的项目中的package.json文件。
2) 改变你项目中的 @react-navigation/stack
到版本 5.x.x
.
例子:
"@react-navigation/stack": "^5.2.14",
3) 运行 npm install
.
4)在你的屏幕A,
this.props.navigation.navigate('DetailScreen', {
onNavigateBack: (commentText) => this.refresh(commentText)
})
refresh(commentText) {
alert('alert me')
}
5)在你的屏幕D。
this.props.route.params.onNavigateBack(this.state.commentText);
this.props.navigation.goBack();
6)运行 npm start
并重新启动你的项目。
你将会解决这个问题。
请确保您使用的是 @react-navigation/stack: ^5.x.x
下面是一个工作实例...
你正试图在一个子类中访问导航道具。要做到这一点,你需要使用 withNavigation
高阶组件。
import { withNavigation } from 'react-navigation';
// <YOUR COMPONENT>
export default withNavigation(YouChildComponent);
这提供了 navigation
支持到子组件。你可以阅读更多 此处
希望对大家有所帮助。