简体   繁体   English

React / JS 如何检测组件是否被点击但内部没有任何内容

[英]React / JS how to detect if component is being clicked but not anything inside

Not sure if this problem matches React or vanilla JS.不确定这个问题是否与 React 或 vanilla JS 匹配。

but if I have this code:但如果我有这段代码:

<div>
    <span>Test</Span>
</div>

I want to detect if someone clicked on the div element, but not on the span element or anything else inside the div.我想检测是否有人点击了 div 元素,但没有点击 span 元素或 div 内的任何其他元素。

how can it be done?如何做呢?

An example to a div with reference ( React feature ):带有参考的 div 示例(React 功能):

<div ref={this.refEl}>
     <span>Test</span>
</div>

and above that code, inside the render I could do:在该代码之上,在render中我可以这样做:

this.refElement = React.createRef();

And now I have a reference to that element, but now how can I do that?现在我有了那个元素的引用,但现在我该怎么做呢?

You can compare event.currentTarget and event.target .您可以比较event.currentTargetevent.target When they are equal, the element with the event listener was clicked.当它们相等时,具有事件侦听器的元素被单击。 When they are NOT equal, a child was clicked.当他们不相等时,一个孩子被点击。

Here's a full example:这是一个完整的例子:

 const h1 = document.querySelector('h1') const section = document.querySelector('section') section.addEventListener('click', (event) => { if (event.currentTarget === event.target) { h1.innerText = 'You clicked the section' } else { h1.innerText = `You clicked the ${event.target.tagName.toLowerCase()} inside the section` } })
 section { background-color: lightgreen; padding: 20px; } section, article, section h1 { padding: 10px; color: white; font-weight: bold; margin: 10px; } article { background-color: lightblue; padding: 20px; } section h1 { background-color: lightcoral; } body { font-family: sans-serif; } h2 { text-align: center; padding-top: 30px; }
 <h1>Try clicking the colored boxes...</h1> <section> Section <article> Article <h1>Heading</h1> </article> </section>

If you're using this in a React app then your onClick handler should use event.stopPropagation() when you don't want the click to be registered by elements that aren't targetted.如果您在 React 应用程序中使用它,那么当您不希望点击被非目标元素注册时,您的onClick处理程序应该使用event.stopPropagation()

Here's an example of a React component using this in action.这是一个实际使用此功能的 React 组件示例。

import React from 'react'

const MyComponent = () => {
  function handleDivClick() {
    console.log('div clicked')
  }

  function handleSpanClick(e) {
    e.stopPropagation()
    console.log('span clicked')
  }

  return (
    <div onClick={handleDivClick}>
      <span onClick={handleSpanClick}>
        Content
      </span>
    </div>

  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM