React Native v0.66.1版本中TouchableOpacity运行异常如何解决?
React Native 0.66.1 + react-native-gesture-handler + Reanimated 2 下TouchableOpacity异常修复方案
异常现象:
解决方案
- 替换TouchableOpacity导入来源
停止使用React Native自带的TouchableOpacity,改为从react-native-gesture-handler中导出的适配版本,该组件默认适配手势库的响应逻辑,不会与Reanimated 2的动画线程产生冲突:// 移除原导入 // import { TouchableOpacity } from 'react-native' // 替换为 import { TouchableOpacity } from 'react-native-gesture-handler' - 适配动画场景需求
如果需要给TouchableOpacity绑定Reanimated动画属性,需先将组件转换为Animated适配版本:import Animated from 'react-native-reanimated' import { TouchableOpacity } from 'react-native-gesture-handler' const AnimatedTouchableOpacity = Animated.createAnimatedComponent(TouchableOpacity) - 调整手势响应优先级
若页面外层配置了PanGesture、TapGesture等自定义手势,需添加优先级配置避免手势冲突:给外层手势添加failOnTouchGesture={true}属性,或通过waitFor参数指定外层手势等待触控组件的响应完成后再触发。 - 确认依赖版本适配
React Native 0.66.1版本需匹配对应兼容的第三方库版本,避免版本不兼容导致的底层异常:- react-native-gesture-handler >= 1.10.3
- react-native-reanimated >= 2.2.4
- 校验基础配置项
- 确认项目入口文件(通常为index.js)最顶部已导入react-native-gesture-handler:
import 'react-native-gesture-handler'- 确认babel.config.js中已正确添加Reanimated 2的插件配置(该插件必须放在plugins数组末尾):
module.exports = { presets: [ 'module:metro-react-native-babel-preset' ], plugins: [ // 其他插件 'react-native-reanimated/plugin' ] }
配置修改完成后执行如下命令清理缓存重启项目即可生效:npx react-native start --reset-cache
内容的提问来源于stack exchange,提问作者Muhammad Rafeh Atique
相关产品推荐
相关产品推荐

