需求背景
比如说有一个弹窗组件, 每一个页面都需要使用, 但我们在每个页面都引入一边组件会非常麻烦, 于是想了下面这个方法, 用于通过js控制组件在任意页面展示组件
import Taro from '@tarojs/taro'
import ReactDom from 'react-dom'
// 插槽节点的id
const portalId = 'portalId'
// 当前所有页面的页面栈
const currentPages = Taro.getCurrentPages()
// 想要弹窗的页面(本文默认选用了最后一个页面, 也可以通过routePath匹配, 或者其他的一些方案)
const currentPage = currentPages[currentPages.length - 1]
// 获取到当前的jsx挂载的根节点
const root = document.getElementById(currentPage?.$taroPath)
// 尝试获取插槽节点的虚拟dom
let portal = document.getElementById(portalId)
if (root) {
if (!portal) {
// 如果没有插槽节点则主动创建一个
portal = document.createElement('view')
// 给插槽节点赋值上固定id
portal.id = portalId
}
if (portal) {
// 将插槽节点放入到跟节点中
root.appendChild(portal)
// 创建一个移除组件的方法, 本文通过子组件的按钮进行移除, 也可用定时器移除, 实现toast效果
const onClose = () => ReactDOM.unmountComponentAtNode(portal)
// 通过ReactDom将我们的Demo组件挂载到页面中
ReactDOM.render(<Demo onClose={onClose} />, portal)
}
}