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

Expo React Native Web如何适配浏览器返回按钮?

在Expo + React Native Web中实现浏览器返回按钮功能

当然可以实现浏览器返回按钮的功能,问题出在你当前的NavigationContainer没有配置与浏览器历史记录同步的机制。以下是具体的解决步骤:

1. 安装依赖

首先确保安装history包,React Navigation需要它来管理浏览器历史:

npm install history
# 或者使用yarn
yarn add history

2. 修改App.js配置

创建浏览器历史实例并传递给NavigationContainer,这样导航操作会同步到浏览器历史记录:

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { createBrowserHistory } from 'history';

const Stack = createNativeStackNavigator();
// 创建浏览器历史实例
const history = createBrowserHistory();

const App = () => {
  // ... 你的其他业务代码
  return (
    <NavigationContainer history={history}>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{ headerShown: false }}
        />
        <Stack.Screen
          name="Settings"
          component={SettingsScreen}
          options={{ headerShown: false }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  )
};

export default () => {
  return (
    <App />
  );
};

3. 验证效果

启动Expo Web服务:

expo start --web

现在切换页面时,浏览器地址栏会更新对应的路由路径,点击浏览器的返回/前进按钮就能正常触发页面导航,完全符合Web用户的操作直觉。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:25:17