传送组件
vue中有
Teleport组件可以把dom元素"传送"到某节点上
现在拿react实现一份
具体的api好像是createPortal 让我用一下试一下
父组件:点击展示Dialog
// src\pages\index.tsx
import RiModel from '@/components/RiModel'
import { useState } from 'react'
function Home() {
const [isShow, setIsShow] = useState(false)
const hdlClick = () => {
setIsShow(!isShow)
}
return (
<>
<button type="button" onClick={hdlClick}>展示对话框</button>
{isShow && <RiModel hdlClick={hdlClick} />}
</>
)
}
export default Home
子组件:对话框
// src\components\RiModel\index.tsx
import React from 'react'
import { createPortal } from 'react-dom'
interface Props {
hdlClick: () => void
}
const RiModel: React.FC<Props> = function ({ hdlClick }) {
return (
<>
{
createPortal(
<div className="flex justify-center w-full h-full bg-gray-500/10 fixed z-50 top-0 left-0" onClick={hdlClick}>
<div className="h-64 w-[512px] bg-white mt-[20vh] rounded-lg" onClick={e => e.stopPropagation()}>
<div className="font-bold">Dialog Title</div>
</div>
</div>,
document.body,
)
}
</>
)
}
export default RiModel
验证过该组件确实被传送到body下了