React prevent event bubbling in nested components on click

前端 未结 8 1518
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 02:41

Here\'s a basic component. Both the

    and
  • have onClick functions. I want only the onClick on the
  • to fir
8条回答
  •  再見小時候
    2020-11-27 02:58

    This is not 100% ideal, but if it is either too much of a pain to pass down props in children -> children fashion or create a Context.Provider/Context.Consumer just for this purpose), and you are dealing with another library which has it's own handler it runs before yours, you can also try:

       function myHandler(e) { 
            e.persist(); 
            e.nativeEvent.stopImmediatePropagation();
            e.stopPropagation(); 
       }
    

    From what I understand, the event.persist method prevents an object from immediately being thrown back into React's SyntheticEvent pool. So because of that, the event passed in React actually doesn't exist by the time you reach for it! This happens in grandchildren because of the way React handle's things internally by first checking parent on down for SyntheticEvent handlers (especially if the parent had a callback).

    As long as you are not calling persist on something which would create significant memory to keep creating events such as onMouseMove (and you are not creating some kind of Cookie Clicker game like Grandma's Cookies), it should be perfectly fine!

    Also note: from reading around their GitHub occasionally, we should keep our eyes out for future versions of React as they may eventually resolve some of the pain with this as they seem to be going towards making folding React code in a compiler/transpiler.

提交回复
热议问题