父子组件都有按钮,当点击子按钮时,父按钮被调用

Parent and child component both have button, when click child button, parent button invoked

https://i.stack.imgur.com/JgJTQ.png

我这里有一个按钮,父组件是整个黑色块,而子组件是被蓝色包围的按钮。两者都有 onclick 功能。当我点击蓝色按钮时,反而触发了父组件的onclick效果。如何在子组件内部点击时触发子组件的onclick效果?

这叫做event bubbling

when you click the button you're also implicitly clicking the element it is inside.

基本上,当您单击一个元素时,它会继续“冒泡”到 DOM 的顶部,为每个元素调用 onClick。

您可以使用 event.stopPropagation() 来防止这种情况发生。

button.addEventListener('click', e => {
  e.stopPropagation();
  // other stuff
});