javascript - React / JS如何检测组件是否被点击但内部没有任何东西
问题描述
不确定这个问题是否与 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.currentTarget
和event.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>