ReactNative入门——导航和路由
import React from 'react';
import { View, Text, Button } 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 back to Home"
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 Native和React Navigation库创建了一个简单的导航应用。它定义了两个页面组件HomeScreen
和DetailsScreen
,并通过React Navigation的createStackNavigator
创建了一个堆栈导航器,最后通过NavigationContainer
提供了一个包含这个堆栈导航器的容器,使得用户可以在不同的屏幕间导航。
评论已关闭