React Navigation类组件报错:props标题需为字符串及页面跳转异常
错误原因分析
- 初始路由名称不匹配:App.js中
Stack.Navigator的initialRouteName设置为'Profile Page',但对应的Stack.Screen的name属性是"Profile",导航器无法找到对应路由,导致组件初始化时props传递异常。 - 类组件构造函数未传递props:
ProfileScreen的构造函数中调用super()时未传入props,虽不影响render阶段,但不符合React类组件规范,可能引发潜在的props获取问题。 - 冗余依赖冲突:
package.json中包含web端路由包react-router-dom,与React Native专用的React Navigation可能产生冲突。
修复步骤
1. 修正App.js中的初始路由配置
将initialRouteName改为与Stack.Screen的name一致的"Profile",同时确保正确导入页面组件:
import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import ProfileScreen from './Profile'; import BathroomSelectionScreen from './BathroomSelection'; const Stack = createNativeStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator initialRouteName='Profile'> <Stack.Screen name="Profile" component={ProfileScreen}/> <Stack.Screen name="Bathroom" component={BathroomSelectionScreen} /> </Stack.Navigator> </NavigationContainer> ); }
2. 修正ProfileScreen的构造函数
在构造函数中接收并传递props给super:
import React, { Component } from 'react'; import { Button, Text, View} from 'react-native'; class ProfileScreen extends Component { constructor(props){ super(props); } render() { return ( <View> <Text>Bathroom</Text> <Button title="Press me" onPress={() => this.props.navigation.navigate("Bathroom")} /> </View> ); } } export default ProfileScreen;
3. 移除冗余依赖
卸载web端路由包react-router-dom,避免与React Navigation冲突:
expo uninstall react-router-dom # 或使用npm npm uninstall react-router-dom
验证修复
完成上述修改后,重新运行项目,Profile页面的按钮即可正常触发跳转到Bathroom页面,不再出现"The title of a prop must be a string"错误。
内容的提问来源于stack exchange,提问作者Davion Williams Jr.
相关产品推荐
相关产品推荐

