React开发Instagram克隆:实现图片删除确认模态框求助
实现删除确认模态框的优化方案
直接给你修改后的完整代码,已经加入了删除确认的模态框逻辑,点击删除按钮会弹出确认框,确认后才执行删除操作:
import getPhotoUrl from 'get-photo-url' import { useLiveQuery } from 'dexie-react-hooks' import { useState } from 'react' import { db } from '../dexie' const Gallery = () => { const allPhotos = useLiveQuery(() => db.gallery.toArray(), []) const [confirmDeleteId, setConfirmDeleteId] = useState(null) const addPhoto = async () => { db.gallery.add({ url: await getPhotoUrl('#addPhotoInput'), }) } const handleConfirmDelete = () => { if (confirmDeleteId) { db.gallery.delete(confirmDeleteId) setConfirmDeleteId(null) } } return ( <> {confirmDeleteId && ( <div className="modal-overlay"> <div className="modal-content"> <p>确定要删除这张图片吗?</p> <div className="modal-buttons"> <button className="confirm-btn" onClick={handleConfirmDelete}> 确认删除 </button> <button className="cancel-btn" onClick={() => setConfirmDeleteId(null)}> 取消 </button> </div> </div> </div> )} <input type="file" name="photo" id="addPhotoInput"/> <label htmlFor="addPhotoInput" onClick={addPhoto}> <i className="add-photo-button fas fa-plus-square"></i> </label> <section className='gallery'> {!allPhotos && <p>Loading...</p>} {allPhotos?.map((photo) => ( <div className="item" key={photo.id}> <img src={photo.url} className="item-image" alt=""/> <button className="delete-button" onClick={() => setConfirmDeleteId(photo.id)}> Delete </button> </div> ))} </section> </> ) } export default Gallery
关键改动说明
- 状态管理:用
confirmDeleteId存储需要确认删除的图片ID,为空时模态框隐藏;点击删除按钮时赋值,触发模态框显示。 - 模态框结构:新增全屏遮罩的模态框,包含确认/取消按钮,样式可根据项目需求调整。
- 删除逻辑拆分:原直接删除的逻辑移到
handleConfirmDelete,仅在用户确认后执行;取消按钮仅清空状态,不执行删除。 - 样式补充:可以把下面的基础CSS加到项目样式文件里,保证模态框显示正常:
.modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; z-index: 1000; } .modal-content { background: white; padding: 2rem; border-radius: 8px; text-align: center; } .modal-buttons { margin-top: 1rem; display: flex; gap: 1rem; justify-content: center; } .modal-buttons button { padding: 0.5rem 1rem; border: none; border-radius: 4px; cursor: pointer; } .confirm-btn { background: #e74c3c; color: white; } .cancel-btn { background: #bdc3c7; }
内容的提问来源于stack exchange,提问作者Skywalker5
相关产品推荐
相关产品推荐

