React Native通知页现有FlatList如何添加滑动删除功能?
实现列表滑动删除的方案
你可以使用React Native生态通用的react-native-gesture-handler库的Swipeable组件实现该功能,无需手动处理滑动手势逻辑,具体步骤如下:
步骤1:导入依赖
在对应页面的文件头部导入需要的组件:
import { Swipeable } from 'react-native-gesture-handler'; import { TouchableOpacity, Text } from 'react-native';
如果是原生React Native项目,需要先完成该库的原生配置:iOS执行pod install,安卓按照官方文档修改MainActivity配置即可;Expo项目默认内置该库,无需额外配置。
步骤2:改造Card组件,添加滑动操作层
将原有Card外层套上Swipeable组件,配置右滑显示的删除按钮:
Card = ({ product, onDelete }: { product: any, onDelete: () => void }) => { // 定义右滑出现的删除按钮样式 const renderDeleteBtn = () => ( <TouchableOpacity style={{ backgroundColor: '#ff3b30', justifyContent: 'center', alignItems: 'center', width: 80, marginTop: 20 }} onPress={onDelete} > <Text style={{ color: 'white', fontWeight: 'bold' }}>删除</Text> </TouchableOpacity> ); return ( <Swipeable renderRightActions={renderDeleteBtn}> {/* 此处粘贴你原有Card组件的全部代码 */} <View style={{marginTop:20}}> <View style={{ flexDirection: "row" }}> <Image source={product.img}></Image> <View style={{marginLeft: 10}}> <View style={{flexDirection:"row"}}> <Text style={{fontWeight:"bold", color:"#8a8c8f"}}> {product.name} </Text> <Text style={{ color:"#b6b7b9"}}> {" "} {product.time} </Text> </View> {product.follower > 0 ? <View> <View style={{flexDirection: "row"}}> <Text style={{fontWeight:"bold", color:"#8a8c8f"}}>{product.name}</Text> <Text style={{fontWeight:"bold", color:"#b6b7b9"}}>{""} ve {""}</Text> <Text style={{fontWeight:"bold", color:"#8a8c8f"}}>{product.follower}</Text> <Text style={{color:"#b6b7b9"}}>{""} kişi resmine oy verdi{""}</Text> </View> </View> : <Text style={{color:"#b6b7b9"}}> {product.command} </Text> } </View> </View> </View> </Swipeable> ) };
步骤3:添加删除逻辑,修改FlatList配置
在你的组件内编写删除数据的方法,同时调整FlatList的参数:
// 类组件内的删除方法 handleDelete = (productId) => { // 过滤掉要删除的项,更新数据源 this.setState(prev => ({ products: prev.products.filter(item => item.id !== productId) })); // 如需二次确认删除,可在此处添加Alert弹窗逻辑 } // 改造后的FlatList <FlatList style={{ margin: 10, width: "100%" }} numColumns={1} data={this.state.products} keyExtractor={(item) => item.id.toString()} // 必须配置唯一key,没有id可用其他唯一字段替代 renderItem={({ item }) => <this.Card product={item} onDelete={() => this.handleDelete(item.id)} />} />
内容的提问来源于stack exchange,提问作者doğan kısa
相关产品推荐
相关产品推荐

