如何配置react-navigation使其使用哈希URL?
React Navigation 支持哈希路由模式,无需手动在路径中添加#,只需通过配置history实例即可实现,步骤如下:
- 从
history库导入createHashHistory方法 - 在顶层
NavigationContainer组件中传入自定义的哈希历史实例
具体代码示例:
import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; import { createHashHistory } from 'history'; const Stack = createNativeStackNavigator(); // 创建哈希模式的历史对象 const hashHistory = createHashHistory(); export default function App() { return ( // 将哈希历史传入导航容器 <NavigationContainer history={hashHistory}> <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Details" component={DetailsScreen} /> </Stack.Navigator> </NavigationContainer> ); }
配置完成后,路由会自动变为哈希格式,例如https://example.com/#/Home,不会出现#被转义为%23的问题。无论使用哪种导航器(如底部标签导航器),只需在最外层的NavigationContainer中配置该history即可。
内容的提问来源于stack exchange,提问作者Jim B.
相关产品推荐
相关产品推荐

