ReactNative——导航器react-navigation(堆栈式导航器篇)
import React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
// 定义堆栈式导航器
const Stack = createStackNavigator();
// 创建屏幕
function HomeScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
</View>
);
}
function DetailsScreen({ navigation }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Button
title="Go to Details again"
onPress={() => navigation.push('Details')}
/>
<Button
title="Go back"
onPress={() => navigation.goBack()}
/>
</View>
);
}
// 导出应用
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
这段代码展示了如何使用react-navigation
库中的createStackNavigator
来创建一个简单的堆栈式导航器。它定义了两个屏幕HomeScreen
和DetailsScreen
,并通过NavigationContainer
将它们包装起来,形成一个完整的导航应用。在HomeScreen
中,我们使用navigation.navigate
方法导航到DetailsScreen
;在DetailsScreen
中,我们使用navigation.push
方法推送到同一路由的新实例,以及使用navigation.goBack
方法返回上一屏幕。这是React Native开发中使用堆栈式导航器的一个基本示例。
评论已关闭