React: event bubbling through nested components

前端 未结 3 1793
暖寄归人
暖寄归人 2021-02-01 16:13

Let\'s say I have nested components like this:


  
    
      
        
cl
3条回答
  •  执念已碎
    2021-02-01 16:36

    React supports Synthetic Events across it's Virtual DOM in both capturing and bubbling phases (as described here: https://facebook.github.io/react/docs/events.html).

    This means that you could put an onClick handler on any DOM element near the root and it should trigger for all Click events on the page:

    
      
    click me

    However, since it will fire for all click events, you would need to disambiguate between them in the click handler (which makes for some pretty ugly code).

    function handleAllClickEvents(event) {
      var target = event.relatedTarget;
      var targetId = target.id;
      switch(targetId) {
        case 'myBtn1':
          // handle myBtn1 click event
        case 'myBtn2':
          // handle myBtn2 click event
      }
    }
    

    This style of Event Delegation is actually what React does under the hood (https://shripadk.github.io/react/docs/interactivity-and-dynamic-uis.html#under-the-hood-autobinding-and-event-delegation) so you have to ask yourself if that's what you really want to do.

    Alternatively you might want to look at something like the Dispatcher pattern in Flux (https://reactjs.org/blog/2014/07/30/flux-actions-and-the-dispatcher.html). It's a little bit more complicated to get going but it's a better solution overall.

提交回复
热议问题