简体   繁体   English

在Reactjs中的组件之间进行交互的最佳方式是什么?

[英]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 . 我的解决方案(我觉得这相当不可思议)是我从RootApp传递到Child1回调。 When the user does onClick on Child1 the callback is called. 当用户执行上Child1 的onClick回调被调用。 The callback in RootApp then updates the props defined for Child2 . 然后, RootApp中的回调将更新为Child2定义的道具。 Child2 is re-rendered. 重新渲染Child2

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. 回调是一种解决方法,但是当您需要在根目录和子目录之间引入组件,或者需要重构应用程序和重组UI时,回调可能会变得非常麻烦。 You may look at Morearty.js which decouples components using single immutable state data structure. 您可能会看到Morearty.js ,它使用单个不可变状态数据结构解耦组件。 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. 因此,在child的onClick中,您只需更新状态,所有其他依赖于该状态部分的组件都将自动重新呈现。 See the introduction and API docs for more details. 有关更多详细信息,请参见简介和API文档。

Of course you still need callbacks for many valid cases but many of them are elliminated. 当然,对于许多有效的情况,您仍然需要回调,但是其中许多被省略了。

Thanks to trekforever for confirming. 感谢trekforever的确认。 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. 从RootApp传递给Child1的回调。 When the user does onClick on Child1 the callback is called. 当用户在Child1上执行onClick时,将调用回调。 The callback in RootApp then updates the props defined for Child2. 然后,RootApp中的回调将更新为Child2定义的道具。 Child2 is re-rendered. 重新渲染Child2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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