简体   繁体   中英

What is the best way for interacting between Components in Reactjs?

I'm trying to intercept user activity from a child component and then update the state of one of its siblings. Eg

 -RootApp
 --Child1 (has user interaction e.g. onClick)
 --Child2 (needs data from Child1 to update state)

My solution (which I find rather weird) is I have a callback passed to Child1 from RootApp . When the user does onClick on Child1 the callback is called. The callback in RootApp then updates the props defined for Child2 . Child2 is re-rendered.

Am I doing this right?

Callback are the way to go but they may become very cumbersome when you need to introduce a component between the root and the child, or when you need to refactor your app and restructure the UI. You may look at Morearty.js which decouples components using single immutable state data structure. So, in child's onClick you just update the state and all other components which depend on that state section will be re-rendered automatically. See the introduction and API docs for more details.

Of course you still need callbacks for many valid cases but many of them are elliminated.

Thanks to trekforever for confirming. Callbacks are the way for passing states.

This is what I do (as in question):

-RootApp
 --Child1 (has user interaction e.g. onClick)
 --Child2 (needs data from Child1 to update state)

Have a callback passed to Child1 from RootApp. When the user does onClick on Child1 the callback is called. The callback in RootApp then updates the props defined for Child2. Child2 is re-rendered.

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