有一個「門戶」模式,它指定一個元素應該附加到document.body
。我想要類似這樣的東西,但是,它必須附加到特定的組件。我的基本佈局組件將如下所示(Codepen Here):將組件注入到沒有Redux的特定div中
<div className={styles.container}>
<div className={styles.header}>
<Navbar />
</div>
{/* Here be the problem */}
<PortalTarget />
<div className={styles.content}>
<div className={styles.leftSidebar}>
<SidebarNav />
</div>
<div className={styles.main}>
{children}
</div>
</div>
</div>
相反渲染document.body
的,它應該找到PortalTarget
元素(只有一個最理想會被渲染),然後追加<Portal>
成DOM節點。
我在創建和存儲對<PortalTarget>
的引用時遇到了困難,我似乎無法找到一個不使用redux的好方法。
有沒有辦法在React中做到這一點?
你可能會對https://github.com/camwest/react-slot-fill感興趣(儘管我還沒有嘗試過)。 –