简体   繁体   English

如何渲染在APP不同地方定义的同一个React组件实例?

[英]How to render the same instance of a React component that are defined in different places of the APP?

Let's suppose that I have 2 top level components, A and B. The component C will be created inside of both A and B. How do I ensure that the same instance of C is created in both.假设我有 2 个顶级组件,A 和 B。组件 C 将在 A 和 B 内部创建。如何确保在两者中创建相同的 C 实例。 Ie, they are in sync, whatever happens to one the other will automatically update as well.即,它们是同步的,无论彼此发生什么,也会自动更新。

I have tried assigning the same key value to both, but it didn't work.我曾尝试为两者分配相同的键值,但没有奏效。

That is not possible as described.这是不可能的。 React elements in different parts of the tree will always result in different instances.树不同部分的 React 元素总是会产生不同的实例。

The most common way to synchronize the behavior of two parts of the component tree is to lift state up , to a component which is the common ancestor of both components.使组件树的两个部分的行为同步的最常见方法是将 state 提升到一个组件,该组件是两个组件的共同祖先。 This ancestor component implements the logic and state for both descendants, and passes the necessary values down via props (or context if necessary)这个祖先组件实现了两个后代的逻辑和状态,并通过道具(或上下文,如果需要)向下传递必要的值

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

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