简体   繁体   English

在React.js中,我如何设置一个简单的全局事件系统来在组件之间进行通信?

[英]In React.js, how would I set up a simple global event system to communicate between components?

After toying with React a bit, I think I mostly like it, but there are a couple of things I'm struggling to figure out how to do. 在玩了React之后,我觉得我最喜欢它,但是有一些事情我正在努力弄清楚该怎么做。 One of those is basic communication between components that are not in a parent-child relationship. 其中之一是不在父子关系中的组件之间的基本通信。

As I understand from the tutorial, most communication is done via a parent-child relationship using states and props, and that seems simple enough. 正如我从教程中理解的那样,大多数通信是通过使用状态和道具的父子关系完成的,这看起来很简单。 But when there is no parent-child relationship, the docs recommend setting up a global event system and just leave that to me to figure out. 但是当没有父子关系时,文档会建议建立一个全局事件系统,然后让我知道。 Not really sure what is meant by this. 不确定这是什么意思。

Let's take the problem I'm working on as an example. 让我们以我正在研究的问题为例。 I have a <SearchBar /> component in the navbar of my page and I would like to use this to populate search results in a <ResultsTab /> component elsewhere on the page. 我在页面的导航<SearchBar />有一个<SearchBar />组件,我想用它来填充页面上其他地方的<ResultsTab />组件中的搜索结果。 Trying to relate these via a common parent just isn't practical. 试图通过共同的父母来解决这些问题是不切实际的。 So how would I update the ResultsTab with the SearchBar's results? 那么我如何使用SearchBar的结果更新ResultsTab? I'm sure I could just do it via jQuery and forget about React, but what is the proper React way to do this? 我确信我可以通过jQuery做到忘记React,但是React的正确方法是什么?

Facebook have released a pattern called Flux for this - https://github.com/facebook/flux . Facebook已经发布了一个名为Flux的模式 - https://github.com/facebook/flux It can be very verbose in simple applications, but it works well. 它在简单的应用程序中可能非常冗长,但它运行良好。

As with all these things, the community is moving very fast and making a lot of changes. 如同所有的这些事情,社会的发展非常快,做了很大的改动。 I recommend getting used to very basic examples, then read https://medium.com/@dan_abramov/the-evolution-of-flux-frameworks-6c16ad26bb31 and try some of the others. 我建议习惯非常基本的例子,然后阅读https://medium.com/@dan_abramov/the-evolution-of-flux-frameworks-6c16ad26bb31并尝试其他一些例子。

@dan_abramov's https://github.com/gaearon/redux seems very popular at the moment. @ dan_abramov的https://github.com/gaearon/redux目前似乎很受欢迎。

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

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