如何在React.js博客应用中实现评论回复框的独立切换功能
解决评论回复框独立显示隐藏的问题
我来帮你搞定这个问题!你现在遇到的问题根源在于用了一个全局的布尔状态showReply来控制所有回复框的显示隐藏,所以点击任何一个评论的Reply按钮,都会同时切换所有回复框的状态。咱们把状态改成存储当前要激活的评论ID就能解决这个问题,具体修改步骤如下:
1. 修改状态定义
把原来的布尔状态改成存储评论ID的状态,初始值设为null(表示没有任何回复框显示):
// 替换原来的const [showReply, setShowReply] = useState(false) const [showReplyId, setShowReplyId] = useState(null)
2. 更新切换函数
修改handleShowReplyComment逻辑,判断当前点击的ID是否和状态中存储的ID一致:如果一致就隐藏回复框(设为null),否则就显示该评论的回复框(存储当前ID):
const handleShowReplyComment = (id) => { // 使用函数式更新来获取之前的状态值 setShowReplyId(prevId => prevId === id ? null : id); }
3. 修改渲染逻辑中的回复框判断
把原来判断showReply布尔值的逻辑,改成判断当前评论的_id是否等于showReplyId:
// 替换原来的{showReply && <div className='reply-div'>...</div>} {showReplyId === _id && <div className='reply-div'> <textarea className='comment-wrapper '> </textarea> </div>}
修改后的完整渲染代码片段
return ( <div className="comment"> <h5 className='users-comment'>Users comments</h5> {comments.map((singleComment, index)=>{ console.log(singleComment) const {author, commentdescription, _id, createdAt} = singleComment return( <> {updateComment == _id ? <div className='comment-div' key={_id} > <textarea className='comment-wrapper' type='text' onChange={(e) => setCommentDescription(e.target.value)} value={commentdescription2}> </textarea> <button className={isLoading ? 'comment-btn-no-cursor comment-btn': 'comment-btn'}onClick={() => handleCommentUpdate(_id)}>Update Post</button> {error && <p>what happened?</p> } </div> : <div className='displayed-comments'key={_id}> <div className="commentPic"> <img className="user-pics" src={PF + singleComment.author.profilePicture} alt="" /> </div> <div className="comment-info"> <div className="comment-author-div"> <div className='comment-author-date-info'> <h4 className="comment-author">{singleComment.author.username}</h4> <p className="comment-date">{new Date(singleComment.createdAt).toDateString()} </p> </div> { singleComment.author.username == user?.username && <div className="comment-edit-delete-div"> <i className="singlePostIcon fas fa-edit" onClick={() => {setUpdateComment(_id); setCommentDescription(commentdescription)}} ></i> <i className={isLoading? "cursor-not-allowed singlePostIcon far fa-trash-alt":"singlePostIcon far fa-trash-alt" } onClick={() => handleCommentDelete(_id)} ></i> </div> } </div> <p className="comment-content">{singleComment.commentdescription}</p> <div> </div> <h5 className="reply-comment" onClick={() => handleShowReplyComment(_id)}>Reply</h5> {showReplyId === _id && <div className='reply-div'> <textarea className='comment-wrapper '> </textarea> </div>} </div> </div> } </> ) })} </div> )
逻辑说明
现在状态showReplyId只会存储当前需要显示回复框的评论ID,每个评论在渲染时只会对比自己的_id和状态中的ID,只有匹配时才会显示回复框,这样就实现了点击哪个评论的Reply按钮,就只切换该评论的回复框状态,不会影响其他评论。
内容的提问来源于stack exchange,提问作者kinhs
相关产品推荐
相关产品推荐

