[英]How do I check if the user clicked inside the current component?
I have a component called Dialog
, in which I attach an event listener on mouse clicks on the window
object. 我有一个名为
Dialog
的组件,在其中我通过鼠标点击window
对象附加一个事件监听window
。
componentDidMount() {
document.addEventListener('click', this.handleClick);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick);
}
How can I detect (in the handleClick
function) whether a click has been fired inside the component or outside? 如何检测(在
handleClick
函数中)是否在组件内部或外部触发了单击? Note that this dialog contains different elements and child components. 请注意,此对话框包含不同的元素和子组件。
parent.contains(child)
is your friend. parent.contains(child)
是你的朋友。 This solution using refs
might not be perfect, but simply using this
does not work as it's not a proper DOM node. 该解决方案利用
refs
可能不是完美的,但简单地使用this
行不通,因为它不是一个适当的DOM节点。 I'm using React 15 here, so keep in mind that in earlier versions you'd have to use .getDOMNode()
on the parent. 我在这里使用React 15,所以请记住,在早期版本中,您必须在父级上使用
.getDOMNode()
。
class Dialog extends React.Component { constructor() { super(); this.handleClick = this.handleClick.bind(this); } componentDidMount() { document.addEventListener('click', this.handleClick); } componentWillUnmount() { document.removeEventListener('click', this.handleClick); } handleClick(e) { if (this.node.contains(e.target)) { console.log('You clicked INSIDE the component.') } else { console.log('You clicked OUTSIDE the component.') } } render() { return( <span ref={node => this.node = node}> Level 0<br/> <span> Level 1.<br/> <span>Level 2.</span> </span> </span> ); } } ReactDOM.render(<Dialog/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="View"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.