在 React 中只捕获父级的 onClick 事件
Capture only parent’s onClick event in React
在 React 中只捕获父级的 onClick 事件:
- 将 onClick 事件处理程序添加到父元素。
- 检查是否
event.target
等于event.currentTarget
。 - 如果两个元素相同,则用户点击了父元素。
const App = () => { const handleParentClick = event => { event.preventDefault(); if (event.target === event.currentTarget) { console.log('parent clicked'); // 👇 your logic here } }; const handleChildClick = event => { console.log('child clicked'); }; return ( <div> <p onClick={handleParentClick}> Parent element <span style={{margin: '2rem'}} onClick={handleChildClick}> Child element </span> </p> </div> ); }; export default App;
我们只想在handleParentClick
单击父元素而不是子元素时运行函数中的逻辑。
在onClick
父级的事件处理程序中,我们必须比较 和 的
event.target
值event.currentTarget
。
target
属性event
为我们提供了对触发事件的元素(被单击的元素)的引用。另一方面,currentTarget
事件的属性返回事件侦听器附加到的元素。
event.currentTarget
属性始终引用事件处理程序已附加到的元素,与 Event.target 相反,
后者
引用
事件发生的元素并且可能是其后代。
If your child element also has an event listener, you can use the
Event.stopPropagation()
method to prevent further propagation of the current event in the capturing and
bubbling phases.
const App = () => { const handleParentClick = event => { event.preventDefault(); console.log('parent clicked'); }; const handleChildClick = event => { // 👇️ stop event propagation (won't trigger parent's onClick) event.stopPropagation(); console.log('child clicked'); }; return ( <div> <p onClick={handleParentClick}> Parent element <span style={{margin: '2rem'}} onClick={handleChildClick}> Child element </span> </p> </div> ); }; export default App;
We used the stopPropagation()
method in the onClick
event handler of the
child element. This means that the parent’s onClick
event won’t get triggered
when the child element is clicked.
By default when the onClick event of the child element is triggered, the event
on the parent element would also get triggered, but the stopPropagation()
method prevents this behavior.