You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React模态框内Anchor与Button无法点击问题排查

React Portal模态框元素无法点击及内容区触发遮罩关闭问题解决

问题1:模态框内、

原因

Bootstrap的navbar组件默认z-index: 1000,你的模态框遮罩层modal-overlay设置的z-index:99远低于该值,导致模态框内容被navbar遮挡,无法接收鼠标事件。此外,模态框内容区的z-index是相对于父元素modal-overlay的层叠上下文,设置z-index:100无法突破父元素的层级限制。

解决办法

修改modal-overlay的z-index为大于1000的值,比如1001:

.modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1001; /* 高于navbar默认的1000 */
}

问题2:点击模态框内容区触发遮罩层关闭事件

原因

事件冒泡机制:点击内容区(modal-dialog)时,click事件会向上冒泡到父元素modal-overlay,触发绑定的关闭事件。

解决办法

在modal-dialog上添加点击事件,阻止事件冒泡到遮罩层:

<div className="modal-dialog" onClick={(e) => e.stopPropagation()}>
    {/* 原有内容 */}
</div>

完整修正后的Modal.tsx

import ReactDOM from "react-dom";
import './Modal.css';
export default function Modal(props:any){
    const handleCloseClick = () => {
        props.onClose();
    };

    const modalContent = (
        <div className="modal-overlay" onClick={handleCloseClick}>
            <div className="modal-dialog" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header d-flex justify-content-between">
                    <span>{props.title}</span>
                    <a href="#" onClick={handleCloseClick}>X</a>
                </div>
                <div className="modal-body">
                    <p>Modal content goes here</p>
                    <button onClick={handleCloseClick}>TEST</button>
                </div>
            </div>
        </div>
    )

    return ReactDOM.createPortal(modalContent, document.body as Element);
}

完整修正后的Modal.css

.modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1001;
}

.modal-dialog {
    width: 500px;
    height: 300px;
    background-color: white;
}

.modal-body {
    padding-top: 10px;
}

.modal-header {
    display: flex;
    justify-content: flex-end;
    font-size: 25px;
}

内容的提问来源于stack exchange,提问作者LNX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 21:38:12