Skip to content
New issue

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

关于在react中addEventListener事件绑定以及点击位置判断 #154

Open
ckinmind opened this issue Jan 8, 2019 · 1 comment
Open

Comments

@ckinmind
Copy link
Owner

ckinmind commented Jan 8, 2019

问题描述:在react环境中,需要判断全局冒泡的点击,如果来自某一区域则不管,除此之外的点击需要做一些副操作,比如讲某个下拉框收起等等

@ckinmind
Copy link
Owner Author

ckinmind commented Jan 8, 2019

问题解决:这个问题拆分成两个问题,一个是react中的事件绑定以及解除绑定,另一个是判断点击区域

class A extends Component {

    constructor(props) {
        super(props)
        this.handleClick.bind(this)
    }

    componentDidMount() {
        window.addEventListener('click', this.handleClick)
    }
    
    componentWillUnmount(){
        window.removeEventListener('click', this.handleClick)
    }

   handleClick(e) {
     const dom = e.target.closest('.organization-action')
    if (dom) {
       // 如果是来自某个区域的点击
    } else {
      // 如果不是来自某个区域的点击
    }
  }

  render() {}

}

MDN: Element.closest()
Element.closest() 方法用来获取:匹配特定选择器且离当前元素最近的祖先元素(也可以是当前元素本身)。如果匹配不到,则返回 null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant