React Native评论列表添加删除按钮后如何实现删除功能咨询
评论删除功能实现方案
1. 修改 CommentList 组件
修改点:新增删除回调属性定义,给删除按钮绑定点击事件传递当前评论索引
import { ScrollView, StyleSheet, Text, View, Button} from 'react-native'; import PropTypes from 'prop-types'; import React from 'react'; export default class CommentList extends React.Component { static propTypes = { items: PropTypes.arrayOf(PropTypes.string).isRequired, // 新增删除回调属性定义 onDeleteComment: PropTypes.func.isRequired, }; renderItem = (item, index) => ( <View key={index} style={styles.comment}> <Text>{item}</Text> <Button // 绑定点击事件,传递当前评论索引 onPress={() => this.props.onDeleteComment(index)} title="Delete" color="black" accessibilityLabel="Delete comments" /> </View> ); render() { const { items } = this.props; return <ScrollView>{items.map(this.renderItem) }</ScrollView>; } } const styles = StyleSheet.create({ comment: { marginLeft: 20, paddingVertical: 20, paddingRight: 20, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: 'black', }, });
2. 修改 Comments 父组件
修改点:新增删除回调属性透传,将上层传入的删除方法传给 CommentList
import { SafeAreaView, ViewPropTypes, Button} from 'react-native'; import PropTypes from 'prop-types'; import React from 'react'; import NavigationBar from '../components/NavigationBar'; import CommentList from '../components/CommentList'; import CommentInput from '../components/CommentInput'; export default function Comments({ style, onSubmitComment, onClose, comments, // 接收上层传入的删除回调 onDeleteComment, }) { return ( <SafeAreaView style = {style}> <NavigationBar title="Comments" leftText= 'Close' onPressLeftText= {onClose} /> <CommentInput placeholder = "Leave a Comment" onSubmit={onSubmitComment} /> {/* 给 CommentList 传递删除回调 */} <CommentList items ={comments} onDeleteComment={onDeleteComment} /> </SafeAreaView> ); } Comments.propTypes = { style: ViewPropTypes.style, comments: PropTypes.arrayOf(PropTypes.string).isRequired, onClose: PropTypes.func.isRequired, onSubmitComment: PropTypes.func.isRequired, // 新增删除回调属性定义 onDeleteComment: PropTypes.func.isRequired, }; Comments.defaultProps = { style: null, };
3. 上层存储评论的页面补充删除逻辑
评论数组存储在引入 Comments 组件的上层页面 state 中,需要在上层实现具体的删除逻辑,示例如下(函数组件写法,类组件同理修改state即可):
import React, { useState } from 'react'; import Comments from './Comments'; export default function UpperPage() { // 原有的评论存储state const [comments, setComments] = useState(['测试评论1', '测试评论2']); // 原有提交评论逻辑 const handleSubmitComment = (text) => { setComments(prev => [...prev, text]); }; // 新增删除评论逻辑 const handleDeleteComment = (deleteIndex) => { // 过滤掉对应索引的评论,返回新数组更新state setComments(prevComments => prevComments.filter((_, index) => index !== deleteIndex)); }; return ( <Comments comments={comments} onSubmitComment={handleSubmitComment} onDeleteComment={handleDeleteComment} onClose={() => {/* 原有关闭逻辑 */}} /> ) }
注意事项
如果后续评论存在排序、头部插入等操作,建议给每条评论生成唯一ID,替代索引作为删除标识和列表key,避免索引错位导致删错内容的问题。
内容的提问来源于stack exchange,提问作者eight-ply
相关产品推荐
相关产品推荐

