简体   繁体   中英

Propagate event from deeply nested Child Component to Top Level component in React

The following is my component tree.

DashboardComponent
  TaskManagementView
    TaskManagementForm
      SubmitButtonComponent

I need to pass the button clicked event from SubmitButtonComponent to the DashboardComponent .

One way of doing this would be as follows

<DashboardComponenet AddTask={AddSomeTask}>
  ....
  <TaskMangementView submitClicked={props.AddTask}>
    ....
    <TaskManagementForm ButtonClick={props.submitClicked}/>
      .....
      <SubmitButtonComponent onclick={props.ButtonClick}/>
      ....
    <TaskManagementForm />
    ....
  </TaskManagementView >
  ....
</DashboardComponent>

Is there some good way of passing the onClick to the DashboardComponent ? This is hard to maintain.

As Gaurav said, you can either pass the function down through the components as props. But this can get messy when there are many components in the middle

OR

I would recommend using something like Context which will allow you to skip components in the middle and just access the function where needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM