在React中关闭Modal有多种方式,以下是其中几种常见的方法:
import React, { useState } from 'react';
function ParentComponent() {
const [showModal, setShowModal] = useState(false);
const closeModal = () => {
setShowModal(false);
};
return (
<div>
<button onClick={() => setShowModal(true)}>打开Modal</button>
{showModal && (
<div className="modal">
<div className="modal-content">
<button onClick={closeModal}>关闭Modal</button>
{/* Modal内容 */}
</div>
</div>
)}
</div>
);
}
import React, { useRef } from 'react';
function Modal() {
const modalRef = useRef(null);
const closeModal = () => {
modalRef.current.style.display = 'none';
};
return (
<div className="modal" ref={modalRef}>
<div className="modal-content">
<button onClick={closeModal}>关闭Modal</button>
{/* Modal内容 */}
</div>
</div>
);
}
以上是几种常见的关闭Modal的React方式,具体选择哪种方式取决于项目的需求和个人偏好。
领取专属 10元无门槛券
手把手带您无忧上云