We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在使用antd的带弹出层的组件时,当点击弹出层以外的地方时,都会帮你关闭弹出层,最近在徐州中做的组件需要这样的功能,下面简单介绍下如何实现:
antd
rc-util
react-dom
findDOMNode
import addEventBodyListener from 'rc-util/lib/Dom/addEventListener'; import contains from 'rc-util/lib/Dom/contains'; import { findDOMNode } from 'react-dom';
refs
<div visible={this.state.visible} ref={ref => (this.modalRef = ref)}>modal</div>
componentDidUpdate
document.body
componentDidUpdate() { if (this.state.visible) { this.clickOutside = addEventBodyListener(document.body, 'mousedown', this.onDocumentClick) return; } }
onDocumentClick
onDocumentClick = e => { const modalRef = findDOMNode(this.modalRef); // 检测`e.target`是否不是`modalRef`或`modalRef`的子元素 // 即点击目标不在弹出层上时,关闭弹出层 // 必要时需要将触发弹出层打开的按钮也要算在弹出层以外的目标区域 if (!contains(modalRef, e.target)) { this.setState({ visible: false }) } }
componentDidUpdate() { if (this.clickOutside) { this.clickOutside.remove(); } } componentWillUnmount() { if (this.clickOutside) { this.clickOutside.remove(); } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
在使用
antd
的带弹出层的组件时,当点击弹出层以外的地方时,都会帮你关闭弹出层,最近在徐州中做的组件需要这样的功能,下面简单介绍下如何实现:rc-util
中的一些工具方法和react-dom
的findDOMNode
方法refs
componentDidUpdate
声明周期中为document.body
添加监听事件onDocumentClick
点击方法:如果当前点击的区域不在指定区域内,则关闭弹出层componentDidUpdate
中的监听也需要移除The text was updated successfully, but these errors were encountered: