检测点击React组件外面 [英] Detect click outside React component

查看:73
本文介绍了检测点击React组件外面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来检测点击事件是否发生在组件外部,如文章。 jQuery nearest()用于查看点击事件中的目标是否将dom元素作为其父项之一。如果有匹配,点击事件属于其中一个孩子,因此不被认为是组件外。

I'm looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the the target from a click event has the dom element as one of its parents. If there is a match the click event belongs to one of the children and is thus not considered to be outside of the component.

所以在我的组件中,我想附加一个点击处理程序到窗口。当处理程序触发时,我需要将目标与我的组件的dom子项进行比较。

So in my component I want to attach a click handler to window. When the handler fires I need to compare the target with the dom children of my component.

点击事件包含类似path的属性,似乎保持dom路径活动已经走过。我不知道要比较什么或如何最好地遍历它,我认为有人必须已经把它放在一个聪明的效用函数中?否?

The click event contains properties like "path" which seems to hold the dom path that the event has travelled. I'm not sure what to compare or how to best traverse it, and I'm thinking someone must have already put that in a clever utility function... No?

推荐答案

我发现一个解决方案感谢Ben Alpert在discuss.reactjs.org 。建议的方法将一个处理程序附加到文档中,但是证明是有问题的。单击我的树中的一个组件导致重新移植,删除更新时单击的元素。因为React的rerender在之前发生了文档主体处理程序,所以元素没有被检测为内部树。

I found a solution thanks to Ben Alpert on discuss.reactjs.org. The suggested approach attaches a handler to the document but that turned out to be problematic. Clicking on one of the components in my tree resulted in a rerender which removed the clicked element on update. Because the rerender from React happens before the document body handler is called, the element was not detected as "inside" the tree.

解决方案这就是在应用程序根元素上添加处理程序。

The solution to this was to add the handler on the application root element.

main:

window.__myapp_container = document.getElementById('app')
React.render(<App/>, window.__myapp_container)

component:

component:

import { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';

export default class ClickListener extends Component {

  static propTypes = {
    children: PropTypes.node.isRequired,
    onClickOutside: PropTypes.func.isRequired
  }

  componentDidMount () {
    window.__myapp_container.addEventListener('click', this.handleDocumentClick)
  }

  componentWillUnmount () {
    window.__myapp_container.removeEventListener('click', this.handleDocumentClick)
  }

  /* using fat arrow to bind to instance */
  handleDocumentClick = (evt) => {
    const area = ReactDOM.findDOMNode(this.refs.area);

    if (!area.contains(evt.target)) {
      this.props.onClickOutside(evt)
    }
  }

  render () {
    return (
      <div ref='area'>
       {this.props.children}
      </div>
    )
  }
}

这篇关于检测点击React组件外面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆