簡體   English   中英

React / JS 如何檢測組件是否被點擊但內部沒有任何內容

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

不確定這個問題是否與 React 或 vanilla JS 匹配。

但如果我有這段代碼:

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

我想檢測是否有人點擊了 div 元素,但沒有點擊 span 元素或 div 內的任何其他元素。

如何做呢?

帶有參考的 div 示例(React 功能):

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

在該代碼之上,在render中我可以這樣做:

this.refElement = React.createRef();

現在我有了那個元素的引用,但現在我該怎么做呢?

您可以比較event.currentTargetevent.target 當它們相等時,具有事件偵聽器的元素被單擊。 當他們不相等時,一個孩子被點擊。

這是一個完整的例子:

 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>

如果您在 React 應用程序中使用它,那么當您不希望點擊被非目標元素注冊時,您的onClick處理程序應該使用event.stopPropagation()

這是一個實際使用此功能的 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