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 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 Native应用中使用React Navigation库来创建一个简单的堆栈导航。代码定义了两个屏幕:HomeScreen和DetailsScreen,并展示了如何通过按钮触发导航操作。这是学习React Native开发的一个基本示例。