function createPortal( children: ReactNodeList, container: Container, key: ?string = null, ): ReactPortal { return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, key: key == null ? null : '' + key, children, containerInfo: getContainer(container), implementation: null, }; }
React Portal是一种特殊的React元素,它具有独特的类型标识符REACT_PORTAL_TYPE,此外,Portal还需要一个指向实际DOM节点的引用,这个引用可以通过containerInfo属性获取。React Portal的渲染是通过ReactDOM.render方法实现的,具体的渲染过程与普通的React元素相同,只是将渲染结果插入到Portal的指定DOM节点中,而不是插入到根节点中。
在Portal渲染之前,还需要将Portal元素从其父元素的子节点列表中移除。这是通过ReactChildReconciler模块中的moveChild方法实现的。移除操作完成后,Portal元素的containerInfo属性将被设置为null,以便在Portal被卸载时清除对DOM节点的引用。
使用Portal需要注意以下事项:• creactPortal的冒泡依然存在。creactPortal与render不同,React Portal 之所以能够保留事件冒泡行为,是因为 Portal 并不是在全局创建一个独立的 DOM 节点,而是将组件的子树渲染到了指定的目标 DOM 节点中。因此,这些组件仍然保留了事件冒泡行为。