模式句柄外部单击



我的 React 应用程序中有一个模态,当用户点击退出它时,我正在关闭模态。功能如下:

handleOutsideClick = (evt) => {
const { handleClose } = this.props
if(!_isNull(this.modal)) {
if(!this.modal.contains(evt.target)) {
handleClose()
}
}
}

模态div 当然有ref={ node => (this.modal = node) }。现在我在模态中有一个动态表单:用户添加值,它们像"芯片"一样可视化,可以删除......但是问题来了...如果我通过单击它删除一些芯片,它会从 DOM 中删除并且模态关闭,因为条件!this.modal.contains(evt.target)计算结果为true.如何解决这个问题?

我的模态代码在这里:

<div className={ `modal-overlay ${ open ? 'visible' : ''}` }>
<div 
ref={ node => (this.modal = node) }
className={ `modal ${className ? className : ''}` }
>
<header>
<h3>{ title }</h3>
{ !hideCloseButton && 
<IconButton className="close-button" color="grey" handleClick={ handleClose }>
<FontAwesomeIcon icon={ ['far', 'times'] } />
</IconButton>
}
</header>
<section className="modal-body">
{ children }
</section>
</div>
</div>

编辑:我试图添加evt.stopPropagation()到删除芯片功能,但它没有帮助。

您可以添加一个简单的背景:

<div className="modal-backdrop" onClick={this.props.handleClose}></div>

这将覆盖整个屏幕,您只需确保 CSS 中用于分层的z-index正确即可。您希望确保背景位于模态主体后面。

这是我用react-transition-group写的。对我来说就像一个魅力:)

<Transition in={isOpen} timeout={200} unmountOnExit>
{ state => (
<div className={cn.modalWrapper}>
<div className={`${cn.modal} modal-${state} ${size}`}>
<div className={cn.modalBody}>
{ title && 
<div className={cn.modalTitle}>
<h3>{title}</h3>
</div>
} 
{children}
</div>
</div>
<div className={`${cn.modalBackdrop} modal-backdrop-${state}`} onClick={() => handleClose()}></div>
</div>
)}
</Transition>

最新更新