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

React Native Webview menuItems在iOS≥16无法使用的问题求助

解决方案:iOS 16+ 适配 react-native-webview 自定义菜单

问题核心

你当前使用react-native-webview的自定义菜单功能(menuItems+onCustomMenuSelection)在iOS ≤15正常,但iOS ≥16失效,原因是苹果从iOS 16开始弃用UIMenuController,改用UIEditMenuInteraction,而旧版本库的原生实现依赖了已废弃的API。

可行解决方案

方案1:升级至最新版 react-native-webview

官方在后续版本中已完成iOS 16的UIEditMenuInteraction适配,这是最省心的解决方式:

  • 执行升级命令:
    # npm 方式
    npm install react-native-webview@latest
    # yarn 方式
    yarn add react-native-webview@latest
    
  • 升级后重新执行pod install并运行项目,自定义菜单功能会自动恢复,无需修改业务代码。

方案2:手动修改原生代码(无法升级版本时)

若因项目依赖限制无法升级库版本,可按以下步骤修改iOS原生Objective-C代码:

1. 定位目标文件

找到node_modules/react-native-webview/ios/RNCWebView.m文件。

2. 添加UIEditMenuInteraction适配代码

  • 在文件顶部导入头文件:
    #import <UIKit/UIKit.h>
    
  • 在RNCWebView类中添加属性:
    @property (nonatomic, strong) UIEditMenuInteraction *editMenuInteraction;
    
  • 在viewDidLoad方法中初始化交互:
    - (void)viewDidLoad {
        [super viewDidLoad];
        // 保留原有代码,新增以下内容
        self.editMenuInteraction = [[UIEditMenuInteraction alloc] initWithDelegate:self];
        [self addInteraction:self.editMenuInteraction];
    }
    
  • 实现UIEditMenuInteractionDelegate协议方法:
    #pragma mark - UIEditMenuInteractionDelegate
    
    - (UIEditMenuConfiguration *)editMenuInteraction:(UIEditMenuInteraction *)interaction configurationForMenuAtLocation:(CGPoint)location suggestedActions:(NSArray<UIMenuElement *> *)suggestedActions {
        NSMutableArray<UIMenuElement *> *customActions = [NSMutableArray array];
        // 遍历自定义菜单配置,生成UIAction
        for (NSDictionary *item in self.menuItems) {
            UIAction *action = [UIAction actionWithTitle:item[@"label"] image:nil identifier:nil handler:^(UIAction * _Nonnull action) {
                // 触发JS侧的onCustomMenuSelection回调
                [self sendEventWithName:@"onCustomMenuSelection" body:@{@"key": item[@"key"]}];
            }];
            [customActions addObject:action];
        }
        
        UIMenu *customMenu = [UIMenu menuWithTitle:@"" children:customActions];
        return [UIEditMenuConfiguration configurationWithSuggestedActions:suggestedActions customMenu:customMenu];
    }
    
  • 移除原有的UIMenuController相关代码(如canPerformAction:withSender:方法、UIMenuControllerWillShowMenuNotification监听逻辑等)。

3. 编译验证

修改完成后执行pod install,重新运行iOS项目即可生效。

额外提示

  • 手动修改原生代码后,后续升级react-native-webview会覆盖修改,建议用patch-package保存补丁:
    # 安装依赖
    npm install patch-package --save-dev
    # 生成补丁文件
    npx patch-package react-native-webview
    
  • 如需兼容iOS 16以下版本,可通过版本判断分支处理:
    if (@available(iOS 16.0, *)) {
        // UIEditMenuInteraction相关逻辑
    } else {
        // 保留原UIMenuController逻辑
    }
    

内容的提问来源于stack exchange,提问作者Duy Nguyễn Hoàng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:41:04