React Native新手遇依赖错误:无法解析react-native-swiper
解决 "Unable to resolve react-native-swiper" 错误
嘿,我一眼就看出问题所在啦——你安装的包和代码里导入的包根本不是同一个!
你执行的安装命令是:
npm install --save react-native-swipe-gestures
但你在App.js里写的导入语句却是:
import Swiper from 'react-native-swiper';
这就像你买了香蕉,转头找老板要草莓,肯定找不到嘛😅
下面给你两种解决思路,选一种就行:
思路一:改用已安装的 react-native-swipe-gestures
如果你本来就想使用这个手势识别库,那修改App.js的导入语句为正确的包名:
import GestureRecognizer from 'react-native-swipe-gestures';
然后按照这个库的规则写使用代码,比如基础的左滑监听示例:
const swipeConfig = { velocityThreshold: 0.3, directionalOffsetThreshold: 80 }; const handleSwipeLeft = () => { console.log('触发左滑手势啦!'); }; // 在组件中使用 <GestureRecognizer onSwipeLeft={handleSwipeLeft} config={swipeConfig} style={{flex: 1}} > <View style={{flex:1, justifyContent:'center', alignItems:'center'}}> <Text>试试向左滑动我~</Text> </View> </GestureRecognizer>
思路二:安装正确的 react-native-swiper 包
如果你确实需要轮播组件react-native-swiper,那先清理掉装错的包(可选,但更干净),再安装正确的包:
# 卸载错装的手势库 npm uninstall react-native-swipe-gestures # 安装正确的轮播组件 npm install --save react-native-swiper
保持你原来的导入语句不变,就可以正常使用轮播功能了,比如基础的多页轮播示例:
import Swiper from 'react-native-swiper'; // 在组件的render方法中 <Swiper style={{flex:1}} showsButtons={true}> <View style={{backgroundColor:'coral', flex:1, justifyContent:'center', alignItems:'center'}}> <Text>第一页</Text> </View> <View style={{backgroundColor:'skyblue', flex:1, justifyContent:'center', alignItems:'center'}}> <Text>第二页</Text> </View> <View style={{backgroundColor:'limegreen', flex:1, justifyContent:'center', alignItems:'center'}}> <Text>第三页</Text> </View> </Swiper>
最后别忘了重启你的Metro服务器——关掉当前npm start的终端窗口,重新执行npm start,有时候缓存会导致奇怪的问题,重启就搞定啦。
内容的提问来源于stack exchange,提问作者SMcMet
相关产品推荐
相关产品推荐

