我在我的一个项目中使用了stackNavigator 2,如下所示。 从"反应导航"导入 { StackNavigator }
;import {
LoginScreen,
TechStackScreen
} from '../screens';
// Public routes
export const PublicRoutes = StackNavigator({
login: { screen: LoginScreen}
});
// Secured routes
export const SecuredRoutes = StackNavigator({
techStack: { screen: TechStackScreen}
});
但是当我尝试将其与版本 3+ 一起使用时,这不起作用。谁能给我如何使用这样的堆栈导航 3+ 的示例代码?
您需要在根导航器上使用createAppContainer
。这是 v3 中引入的重大更改
StackNavigator
也被createStackNavigator
取代
下面是一个简单的用法示例。
App.js
import React, {Component} from 'react';
import AppContainer from './MainNavigation';
export default class App extends React.Component {
render() {
return (
<AppContainer />
)
}
}
MainNavigation.js
import Screen1 from './Screen1';
import Screen2 from './Screen2';
import { createStackNavigator, createAppContainer } from 'react-navigation';
const screens = {
Screen1: {
screen: Screen1
},
Screen2: {
screen: Screen2
}
}
const config = {
headerMode: 'none',
initialRouteName: 'Screen1'
}
const MainNavigator = createStackNavigator(screens,config);
export default createAppContainer(MainNavigator);
你应该导入并使用createStackNavigator
,这是文档 https://reactnavigation.org/docs/en/stack-navigator.html
只需要对代码进行少量更改
// Public routes
export const PublicRoutes = createStackNavigator({
login: { screen: LoginScreen}
});
// Secured routes
export const SecuredRoutes = createStackNavigator({
techStack: { screen: TechStackScreen}
});
好吧,如果你使用的是StackNavigator,像这样:
// Inside "App.js"
render() {
return (
<NavigationContainer >
<Stack.Navigator >
<Stack.Screen name='Details'
component={ Details } />
</Stack.Navigator >
</NavigationContainer >
)
}
您可以通过访问每个组件可用的属性来使用导航:
// Inside "Details" Component
export default class Details extends React.Component {
render() {
const { navigate } = this.props.navigation
return (
<Button title='Goto Component' onPress={ () => navigate( 'SomeOtherComponent' ) }/>
)
}
}