React中模态框输入内容时自动关闭后重启问题该如何解决?
问题根本原因
你把MyVerticallyCenteredModal组件直接定义在了CommentsList父组件的内部,每次父组件触发重渲染(在输入框输入内容时调用setModalInputComment更新状态就会触发父组件重渲染),React都会重新创建一个全新的MyVerticallyCenteredModal实例,旧的模态框实例被销毁,新的实例挂载,表现出来就是模态框闪一下、关闭又重新打开。
另外你原代码还存在语法错误:useState等Hook、相关处理函数直接写在了组件函数外部,不符合React组件语法规范。
解决方法
把MyVerticallyCenteredModal组件移到CommentsList组件外部,所有模态框需要用到的状态、回调函数都通过props传递即可,修正后完整代码如下:
import React , {useState} from 'react'; import { Button,Form,Modal } from 'react-bootstrap'; // 模态框组件移到父组件外部定义 function MyVerticallyCenteredModal(props) { const { modalInputComment, handleCommentChange, handleCloseModal, onUpdate, ...rest } = props; return ( <Modal {...rest} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Body> <Form> <div className="mb-3"> <label className="col-form-label">Username:</label> <input type="text" className="form-control" id="comment" /> </div> <div className="mb-3"> <label className="col-form-label">Comment:</label> <textarea className="form-control" id="comment-text" value={modalInputComment} onChange={handleCommentChange}></textarea> </div> </Form> </Modal.Body> <Modal.Footer> <Button onClick={onUpdate}>Update</Button> <Button variant='secondary' onClick={handleCloseModal}>Close</Button> </Modal.Footer> </Modal> ); } function CommentsList({ comments }) { const [modalShow, setModalShow] = useState(false); const [modalInputComment, setModalInputComment] = useState(""); // 新增存储当前编辑评论索引的状态,后续更新逻辑会用到 const [currentEditIndex, setCurrentEditIndex] = useState(null); const handleShowModal = (i) => { setCurrentEditIndex(i); // 打开模态框时默认填充原有评论内容 setModalInputComment(comments[i].text); setModalShow(true); } const handleCloseModal = () => { setModalShow(false); setCurrentEditIndex(null); setModalInputComment(""); } const handleCommentChange = (event) => { setModalInputComment(event.target.value); } const handleUpdate = () => { // 此处补充你的更新逻辑,用currentEditIndex和modalInputComment更新对应评论即可 console.log("更新评论索引:", currentEditIndex, "更新后内容:", modalInputComment); handleCloseModal(); } return( <> <div> {comments.map((item,key)=>( <div className="comment" key={key}> <h4>{item.username}</h4> <p>{item.text}</p> <Button variant="outline-primary btn-sm mx-3" onClick={() => handleShowModal(key)}>Update</Button> </div> ))} {/* 所需参数通过props传递给模态框 */} <MyVerticallyCenteredModal show={modalShow} modalInputComment={modalInputComment} handleCommentChange={handleCommentChange} handleCloseModal={handleCloseModal} onUpdate={handleUpdate} /> </div> </> ) }; export default CommentsList;
内容的提问来源于stack exchange,提问作者MagnusEffect
相关产品推荐
相关产品推荐

