我想创建一个Portal组件,它应该附加到它的容器组件,但不是通过容器的ID,而是通过它的ref。换句话说,我不想将document.getElementById('CONTAINER_ID')作为第二个参数传递给ReactDOM.createPortal函数,而是完全依赖于React.forwardRef传递的容器的引用。有没有一种简单的方法来实现这一点?否则,我可能需要先创建一个“附加”到ref的dom节点,然后将该节点作为第二个参数传递给createPortal函数?我希望尽可能避免分配I。以下是示例代码(我在TypeScript中工作):
export default React.forwardRef<HTMLDivElement, Props>( (Props, ref) =>{
const {state, options, dispatch} = Props
if(!state.open) return null
return ReactDOM.createPortal(
<div
className={css`
height: 140px;
background: white;
overflow-y: scroll;
position: absolute;
width:100%;
`}
>
{options}
</div>,
ref.current // <-- THIS DOESN'T WORK
)
}
)
发布于 2021-10-25 00:01:12
当父组件需要访问子组件的元素时,就使用forwardRef
,反之亦然。要将一个元素传递给一个子元素,你需要通过一个道具来完成。此外,由于引用直到第一次呈现后才被填充,因此您可能需要呈现父组件两次,一次是将容器放在页面上,然后再次将其传递给子组件,以便子组件可以创建门户。
const Parent = () => {
const ref = useRef<HTMLDivElement>(null);
const [element, setElement] = useState<HTMLDivElement | null>(null);
useEffect(() => {
// Force a rerender, so it can be passed to the child.
// If this causes an unwanted flicker, use useLayoutEffect instead
setElement(ref.current);
}, []);
return (
<div ref={ref}>
{element && (
<Child element={element} {/* insert other props here */} />
)}
</div>
)
}
const Child = (props: Props) => {
const { state, options, dispatch, element } = props;
if (!state.open) {
return null;
}
return ReactDOM.createPortal(
<div
className={css`
height: 140px;
background: white;
overflow-y: scroll;
position: absolute;
width: 100%;
`}
>
{options}
</div>,
element
);
}
https://stackoverflow.com/questions/69701575
复制相似问题