React Native使用<Swipeable>组件时‘Element type is invalid’错误修复
解决React Native中组件的"Element type is invalid"错误
错误原因分析
你遇到的错误核心问题是Swipeable组件的导入方式错误:
- 导入路径末尾多了不必要的斜杠
/,导致无法正确定位组件文件 Swipeable是react-native-gesture-handler库的命名导出组件,不能使用默认导入的语法import Swipeable from ...
此外,原代码中
修复步骤
修正Swipeable的导入语句
将错误的导入:import Swipeable from 'react-native-gesture-handler/';替换为命名导入:
import { Swipeable } from 'react-native-gesture-handler';为Swipeable绑定侧滑内容
在标签中添加 renderRightActions属性,关联你已定义的getRightContent函数:<Swipeable renderRightActions={getRightContent}>
修正后的完整代码
import React from 'react'; import { StyleSheet, Text, View, TouchableWithoutFeedback, TouchableOpacity, } from 'react-native'; import moment from 'moment'; import { Swipeable } from 'react-native-gesture-handler'; import Icon from 'react-native-vector-icons/FontAwesome'; import 'moment/locale/pt-br'; import commonStyles from '../commonStyles'; export default (props) => { const doneOrNotStyle = props.doneAt != null ? { textDecorationLine: 'line-through' } : {}; const date = props.doneAt ? props.doneAt : props.estimateAt; const formattedDate = moment(date).locale('pt-br').format('ddd, D [de] MMMM'); const getRightContent = () => { return ( <TouchableOpacity style={style.right}> <Icon name="trash" size={30} color="#fff" /> </TouchableOpacity> ); }; return ( <Swipeable renderRightActions={getRightContent}> <View style={style.container}> <TouchableWithoutFeedback onPress={() => props.toggleTask(props.id)}> <View style={style.checkContainer}>{getCheckView(props.doneAt)}</View> </TouchableWithoutFeedback> <View> <Text style={[style.desc, doneOrNotStyle]}>{props.desc}</Text> <Text style={style.date}>{formattedDate}</Text> </View> </View> </Swipeable> ); }; function getCheckView(doneAt) { if (doneAt != null) { return ( <View style={style.done}> <Icon name="check" size={20} color="#fff" /> </View> ); } else { return <View style={style.pending} />; } } const style = StyleSheet.create({ container: { flexDirection: 'row', borderColor: '#AAA', borderBottomWidth: 1, alignItems: 'center', paddingVertical: 10, }, checkContainer: { width: '20%', alignItems: 'center', justifyContent: 'center', }, pending: { height: 25, width: 25, borderRadius: 13, borderWidth: 1, borderColor: '#555', }, done: { height: 25, width: 25, borderRadius: 13, borderWidth: 1, backgroundColor: '#4d7031', alignItems: 'center', justifyContent: 'center', }, desc: { fontFamily: commonStyles.fontFamily, color: commonStyles.colors.mainText, fontSize: 15, }, date: { fontFamily: commonStyles.fontFamily, color: commonStyles.colors.subText, fontSize: 12, }, right: { backgroundColor: 'red', flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', paddingHorizontal: 20, }, });
额外注意事项
确保你已正确安装并配置react-native-gesture-handler:
- iOS:执行
pod install完成依赖安装 - Android:按照库要求在MainActivity中用
GestureHandlerRootView包裹根组件
内容的提问来源于stack exchange,提问作者JulianO Barbosa
相关产品推荐
相关产品推荐

