11import * as React from 'react' ;
22import { createPortal } from 'react-dom' ;
33import canUseDom from 'rc-util/lib/Dom/canUseDom' ;
4+ import { supportRef , useComposeRef } from 'rc-util/lib/ref' ;
45import OrderContext from './Context' ;
56import useDom from './useDom' ;
67import useScrollLocker from './useScrollLocker' ;
@@ -47,7 +48,7 @@ const getPortalContainer = (getContainer: GetContainer) => {
4748 return getContainer ;
4849} ;
4950
50- export default function Portal ( props : PortalProps ) {
51+ const Portal = React . forwardRef < any , PortalProps > ( ( props , ref ) => {
5152 const {
5253 open,
5354 autoLock,
@@ -93,6 +94,15 @@ export default function Portal(props: PortalProps) {
9394 mergedContainer === document . body ) ,
9495 ) ;
9596
97+ // =========================== Ref ===========================
98+ let childRef : React . Ref < any > = null ;
99+
100+ if ( children && supportRef ( children ) && ref ) {
101+ ( { ref : childRef } = children as any ) ;
102+ }
103+
104+ const mergedRef = useComposeRef ( childRef , ref ) ;
105+
96106 // ========================= Render ==========================
97107 // Do not render when nothing need render
98108 // When innerContainer is `undefined`, it may not ready since user use ref in the same render
@@ -103,9 +113,24 @@ export default function Portal(props: PortalProps) {
103113 // Render inline
104114 const renderInline = mergedContainer === false || inlineMock ( ) ;
105115
116+ let reffedChildren = children ;
117+ if ( ref ) {
118+ reffedChildren = React . cloneElement ( children as any , {
119+ ref : mergedRef ,
120+ } ) ;
121+ }
122+
106123 return (
107124 < OrderContext . Provider value = { queueCreate } >
108- { renderInline ? children : createPortal ( children , mergedContainer ) }
125+ { renderInline
126+ ? reffedChildren
127+ : createPortal ( reffedChildren , mergedContainer ) }
109128 </ OrderContext . Provider >
110129 ) ;
130+ } ) ;
131+
132+ if ( process . env . NODE_ENV !== 'production' ) {
133+ Portal . displayName = 'Portal' ;
111134}
135+
136+ export default Portal ;
0 commit comments