1 Star 0 Fork 0

试试才知道/react-click-outside

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
index.js 1.06 KB
一键复制 编辑 原始数据 按行查看 历史
Bernardo Dias 提交于 2018-06-15 08:34 . Fix error with el is null
import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class ClickOutside extends Component {
static propTypes = {
onClickOutside: PropTypes.func.isRequired
}
constructor(props) {
super(props)
this.getContainer = this.getContainer.bind(this)
this.isTouch = false
}
getContainer(ref) {
this.container = ref
}
render() {
const { children, onClickOutside, ...props } = this.props
return <div {...props} ref={this.getContainer}>{children}</div>
}
componentDidMount() {
document.addEventListener('touchend', this.handle, true)
document.addEventListener('click', this.handle, true)
}
componentWillUnmount() {
document.removeEventListener('touchend', this.handle, true)
document.removeEventListener('click', this.handle, true)
}
handle = e => {
if (e.type === 'touchend') this.isTouch = true
if (e.type === 'click' && this.isTouch) return
const { onClickOutside } = this.props
const el = this.container
if (el && !el.contains(e.target)) onClickOutside(e)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/oneGB/react-click-outside.git
git@gitee.com:oneGB/react-click-outside.git
oneGB
react-click-outside
react-click-outside
master

搜索帮助