官网:reactnavigation
1.navigation共三种路由器
- StarkNavigator 堆栈导航
- TabNavigator 底部导航
- DraweNavigator 侧边抽屉导航
2.安装依赖
- yarn add @react-navigation/native
- yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
3.配置app.js
import 'react-native-gesture-handler'; // 放在app.js 或 index.js 最顶部
import {NavigationContainer} from '@react-navigation/native'; //导航器的构建块和共享基础3中导航器必须(导航容器)
4.使用堆栈导航
// Views
import Home from './Views/Home';
import Detail from './Views/Detail';
const Stack = createStackNavigator();
`class App extends Component {
constructor() { // 构造函数
super(); // 调用Component 的构造函数
}
render() {
return (
<>
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: 'pink',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}}>
<Stack.Screen
name="Home"
component={Home}
options={{
title: '首页',
headerRight: () => (
<Button
onPress={() => alert('This is a button!')}
title="Info"
color="blank"
/>
),
}}
/>
<Stack.Screen
name="Detail"
component={Detail}
// options={{
// title: '详情页',
// }}
options={({route}) => {
return {
title: route.params.id,
};
}}
/>
<Stack.Screen
name="Product"
component={Product}
options={{
title: '产品页',
}}
/>
</Stack.Navigator>
</NavigationContainer>
</>
);
}
}
export default App;
5.使用抽屉导航
const Drawer = createDrawerNavigator();
class App extends Component {
constructor() {
super();
}
render() {
return (
<>
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={Home} />
<Drawer.Screen name="Detail" component={Detail} />
</Drawer.Navigator>
</NavigationContainer>
</>
);
}
}
export default App;
6.路由跳转(传参)