门户
用于渲染 DOM 层次结构之外的元素。
用法
¥Usage
Portal
使用 ReactDOM.createPortal
API 在 document.body
或特定容器的末尾渲染元素。
¥The Portal
uses the ReactDOM.createPortal
API to render an element at the
end of document.body
or specific container.
import { Portal } from "@chakra-ui/react"
<Portal>
<div>Portal content</div>
</Portal>
示例
¥Examples
自定义容器
¥Custom Container
使用 container
属性在自定义容器中渲染门户。
¥Use the container
prop to render the portal in a custom container.
import { Portal } from "@chakra-ui/react"
const Demo = () => {
const containerRef = React.useRef()
return (
<>
<Portal container={containerRef}>
<div>Portal content</div>
</Portal>
<div ref={containerRef} />
</>
)
}
已禁用
¥Disabled
使用 disabled
属性禁用门户。这将在同一 DOM 层次结构中渲染子项。
¥Use the disabled
prop to disable the portal. This will render the children in
the same DOM hierarchy.
import { Portal } from "@chakra-ui/react"
const Demo = () => {
return (
<Portal disabled>
<div>Will render the content in place</div>
</Portal>
)
}
服务器渲染
¥Server Rendering
在服务器端渲染 (SSR) 期间,Portal
组件会直接渲染其内容。如果你遇到任何不匹配警告,我们建议你仅在客户端有条件地渲染 Portal
组件。
¥During SSR, the Portal
component directly renders its content. If you run into
any mismatch warnings, we recommended conditionally rendering the Portal
component only on the client-side.
属性
¥Props
Prop | Default | Type |
---|---|---|
as | React.ElementType The underlying element to render. | |
asChild | boolean Use the provided child element as the default rendered element, combining their props and behavior. For more details, read our Composition guide. | |
container | RefObject<HTMLElement | null> | |
disabled | boolean |