React: event bubbling through nested components

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

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


  
    
      
        
cl
相关标签:
3条回答
  • 2021-02-01 16:35

    You can use the shorthand to pass props through to child components

    <Component {...this.props} more="values" />
    

    Transferring props

    So in your case:

    <root />
      <comp1 clickHandler={this.action}/>
        <comp2 {...this.props} />
          <target {...this.props} id={this.props.id} />
            <div onClick={this.props.clickHandler.bind(this, this.props.id)}>click me</div>
    
    0 讨论(0)
  • 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:

    <root>
      <div onClick={this.handleAllClickEvents}>
        <comp1>
          <comp2>
            <target>
              <div id={this.props.id}>click me</div>
    

    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.

    0 讨论(0)
  • 2021-02-01 16:52

    If you want to distinguish which element was clicked at the end, you may use Event object and find there some interesting stuff, such as DOM element type.

    <AnElement>
     <button onClick={e => this.eventHandler(e)}>Click me</button>
     <input type="text" onClick={e => this.eventHandler(e)}>Click me</input>
    
    eventHandler = (e) => {
            console.log(e, e.nativeEvent.toElement.nodeName);
    ...}
    

    And you get button or input depending on what you've clicked. That's what i looked for for my project.

    More over you may find a DOM tree in an array representation

    Hope it helps

    0 讨论(0)
提交回复
热议问题