javascript - React Portals 如何在不同的子树中保存来自提供者的上下文?

标签 javascript reactjs react-context react-portal

因此,Portals 解决的一个有趣且令人惊奇的属性是即使您的组件需要在其他地方呈现,也可以保留 Provider 的 Context。如果您使用 ContextProvider 包装组件子树,则在该子树中呈现的任何组件都可以访问上下文值。

反过来,如果你在子树之外渲染了一些东西,它就无法访问那个上下文。 React Portals 解决了这个问题,所以如果你想在子树之外渲染一些东西,你可以在同一个子树中进行。我认为 React docs touch on this a little :

Features like context work exactly the same regardless of whether the child is a portal, as the portal still exists in the React tree regardless of position in the DOM tree.



我想我并没有概念化这实际上是如何工作的。一个 React Portal 如何可以访问上下文而不需要在同一个子树中呈现?听起来好像在幕后,Portals 是“React Tree”的一部分?所以一定有什么花哨的“传信息,然后渲染门户逻辑”?要清楚我的问题

门户在保留对上下文值的访问方面究竟是如何工作的?

最佳答案

我已经有一段时间没有收到答案了——我希望深入研究 React 的代码,但还没有机会(希望有一天能更新我的答案),但简而言之,它的工作原理是在幕后,React 正在维护它自己的组件树(您可能听说过这称为虚拟 DOM),在其中,创建的组件仍将存在于虚拟 DOM 的 Provider 子树中。
这个article在这里谈一点

Instead of making two calls to ReactDOM.render(), we create two portals and render both under our top-level Provider. ComponentA and ComponentB will be rendered in two different points in the DOM, but they share the same React tree, thanks to portals.

关于javascript - React Portals 如何在不同的子树中保存来自提供者的上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57500580/

相关文章:

javascript - 如何使用 useContext 更改 Context 的值?

javascript - 动态创建整个页面,包括脚本和样式

javascript - js 代码如何使用终端获取输入文件?

node.js - 如何在 React 中显示从 Express 服务器抓取的图像?

javascript - 如何在 Electron 中使用 React Router?

reactjs - 为什么我的 React 上下文没有更新?

javascript - 使用 child 消费者的背景信息

javascript - 作为单位矩阵的最大子矩阵

javascript - ionic : How to make a ng-href link work inside a ui-sref element?

html - 视频 session 像使用css网格的视频网格