React实现类似antd中Modal组件点击Modal组件以外区域隐藏Modal效果

Tips

ReactDOM.findDOMNode(ReactComponent)

获取已渲染到DOM中的组件

Element.conatains(Element)

判断一个元素是否在另一个元素中

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
class Modal extends Component {
state = {
isActive: false,
isMounted: false
}
componentDidMount() {
this.setState({
isMounted: true
})
}
componentDidUpdate(prevProps, prevState) {
if (!prevState.isActive && this.state.isActive) {
document.addEventListener('click', this.hideModal)
}
if (prevState.isActive && !this.state.isActive) {
document.removeEventListener('click', this.hideModal)
}
}
componentWillUnmount() {
document.removeEventListener('click', this.hideModal)
}
hideModal = (e) => {
if (!this.state.isMounted) return false
const node = ReactDOM.findDOMNode(this)
const target = e.target || e.srcElement
const isInside = node.contains(target)
if (this.state.isActive && !isInside) {
this.setState({
isActive: false
})
}
}
showModal = () => {
this.setState({
isActive: true
})
}
render() {
return (
<div>
{this.state.isActive && <div>Modal</div>}
<button onClick={this.showModal}>showModal</button>
</div>
);
}
}
export default Modal;