我们在内部使用 Zag.js,它依赖于 DOM 查询方法,例如 document.querySelectorAll
和 document.getElementById
。在 iframe、Shadow DOM 或 Electron 等自定义环境中,这些方法可能无法按预期工作。
¥We use
Zag.js
internally, which relies on DOM query methods like document.querySelectorAll
and document.getElementById
. In custom environments like iframes, Shadow DOM,
or Electron, these methods might not work as expected.
为了处理此问题,Ark UI 包含 EnvironmentProvider
,允许你设置适当的根节点或文档,以确保正确的 DOM 查询。
¥To handle this, Ark UI includes the EnvironmentProvider
, allowing you to set
the appropriate root node or document, ensuring correct DOM queries.
用法
¥Usage
import { EnvironmentProvider } from "@chakra-ui/react"
<EnvironmentProvider>{/* Your App */}</EnvironmentProvider>
示例
¥Examples
iframe
这是一个在 iframe 环境中使用 react-frame-component
设置 EnvironmentProvider
值的示例。
¥Here's an example that uses react-frame-component
to set the
EnvironmentProvider
's value with the iframe environment.
import { EnvironmentProvider } from "@chakra-ui/react"
import Frame, { FrameContextConsumer } from "react-frame-component"
export const Demo = () => (
<Frame>
<FrameContextConsumer>
{({ document }) => (
<EnvironmentProvider value={() => document}>
{/* Your App */}
</EnvironmentProvider>
)}
</FrameContextConsumer>
</Frame>
)
阴影 DOM
¥Shadow DOM
这是一个在 Shadow DOM 环境中使用 react-shadow
设置 EnvironmentProvider
值的示例。
¥Here's an example that uses react-shadow
to set the EnvironmentProvider
's
value with Shadow DOM environment.
import { EnvironmentProvider } from "@chakra-ui/react"
import { useRef } from "react"
import root from "react-shadow"
export const Demo = () => {
const portalRef = useRef()
return (
<root.div ref={portalRef}>
<EnvironmentProvider
value={() => portalRef?.current?.shadowRoot ?? document}
>
{/* Your App */}
</EnvironmentProvider>
</root.div>
)
}
访问上下文
¥Accessing Context
使用 useEnvironmentContext
钩子访问 RootNode
、Document
和 Window
上下文。
¥Use the useEnvironmentContext
hook to access the RootNode
, Document
, and
Window
context.
import { useEnvironmentContext } from "@chakra-ui/react"
export const Demo = () => {
const { getRootNode } = useEnvironmentContext()
return <pre>{JSON.stringify(getRootNode(), null, 2)}</pre>
}
属性
¥Props
Prop | Default | Type |
---|---|---|
value | RootNode | (() => RootNode) |