You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Expo中layout.tsx的作用及页面导航问题咨询

Expo TypeScript 栈导航页面添加步骤

1. 新建页面组件

在app目录下创建新的TSX文件,比如Profile.tsx,编写基础组件:

import { View, Text, StyleSheet } from 'react-native';

export default function Profile() {
  return (
    <View style={styles.container}>
      <Text>我的个人页面</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

2. 配置layout.tsx中的栈导航

打开app/layout.tsx,找到Stack.Navigator节点,添加新的Stack.Screen路由项:

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Home from './index';
import Profile from './Profile'; // 导入新页面组件

const Stack = createNativeStackNavigator();

export default function RootLayout() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={Home} options={{ title: '首页' }} />
        {/* 添加新页面路由 */}
        <Stack.Screen name="Profile" component={Profile} options={{ title: '个人中心' }} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

3. 在首页添加跳转逻辑

修改app/index.tsx,通过navigation对象实现页面跳转:

import { View, Text, Button, StyleSheet } from 'react-native';
import { StackNavigationProp } from '@react-navigation/native-stack';

// 定义路由参数类型,适配TypeScript类型检查
type RootStackParamList = {
  Home: undefined;
  Profile: undefined;
};

type HomeScreenNavigationProp = StackNavigationProp<RootStackParamList, 'Home'>;

// 接收navigation参数,添加类型注解
export default function Home({ navigation }: { navigation: HomeScreenNavigationProp }) {
  return (
    <View style={styles.container}>
      <Text>首页</Text>
      <Button
        title="跳转到个人页面"
        onPress={() => navigation.navigate('Profile')}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    gap: 20,
  },
});

关键注意事项

  • 确保所有组件都使用TypeScript语法,给props添加正确的类型注解,避免类型报错
  • Stack.Screen的name属性必须和navigation.navigate中传入的名称完全一致
  • 如果使用Expo Router的文件系统路由(而非手动栈导航),只需在app目录下新建对应文件名的TSX文件即可自动生成路由,无需手动配置Stack.Navigator

内容的提问来源于stack exchange,提问作者Ayush Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 07:34:55