react-navigation 6.x总结
React Navigation 6.x是一个流行的库,用于在React Native应用程序中实现导航。以下是一些关键点和示例代码:
- 安装:
npm install @react-navigation/native
- 创建一个基础的栈导航器(Stack Navigator):
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
- 使用选项卡导航器(Tab Navigator):
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
const Tab = createBottomTabNavigator();
function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="Settings" component={SettingsScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
- 导航到另一个屏幕并返回:
// 在HomeScreen组件中
function HomeScreen({ navigation }) {
return (
<View>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
}
// 在DetailsScreen组件中
function DetailsScreen({ navigation }) {
return (
<View>
<Button
title="Go back"
onPress={() => navigation.goBack()}
/>
</View>
);
}
- 使用链式屏幕(Linking screens):
<Stack.Screen name="Profile" component={ProfileScreen} />
- 使用选项配置屏幕:
<Stack.Screen
name="Profile"
component={ProfileScreen}
options={{ title: 'Your Profile' }}
/>
- 使用React Navigation的hooks:
import { useNavigation } from '@react-navigation/native';
function MyComponent() {
const navigation = useNavigation();
return (
<Button
title="Go back"
onPress={() => navigation.goBack()}
/>
);
}
- 处理深链接(Deep linking):
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
i
评论已关闭