> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# Function: createPortal()

> **createPortal**(`vnode`: `ComponentChild`, `container`: `NodesRef`): `ReactNode`

把 `vnode` 渲染到 `container` 中，而不是当前组件在元素树中的位置，同时仍保留在 React 树中。

`container` 是一个 `NodesRef`，可以通过回调 `ref` 或
`lynx.createSelectorQuery().select(...)` 获得。

## Parameters

| Parameter   | Type             | Description                   |
| ----------- | ---------------- | ----------------------------- |
| `vnode`     | `ComponentChild` | 要渲染到 `container` 中的 React 节点。 |
| `container` | `NodesRef`       | 渲染目标 `NodesRef`。              |

## Returns

`ReactNode`

需要在调用处放入 JSX 中的 `ReactNode` 占位符；渲染结果会输出到 `container` 中。

## Remarks

Context 仍会跨越 portal 边界传递，portal 内的状态更新也与其他组件中的表现一致。但有几点行为与 `react-dom`
不同：

- 事件不会沿 React 树冒泡。ReactLynx 沿用 Preact 的做法，
  没有合成事件系统，
  因此事件遵循页面实际的元素结构。
- portal 中的子树仅在后台线程渲染，
  不参与主线程首屏渲染。
- 不支持跨页面或跨 native 容器挂载。

## 示例

**下面是一个示例: react-apis**

**Entry:** `src/create-portal`
**Bundle:** `dist/create-portal.lynx.bundle` | Web: `dist/create-portal.web.bundle`

```tsx
import { createPortal, type ReactNode, root, useState } from "@lynx-js/react";
import type { NodesRef } from "@lynx-js/types";

import "./index.css";

function CreatePortalExample() {
  const [portalHost, setPortalHost] = useState<NodesRef | null>(null);
  const [visible, setVisible] = useState(true);

  const togglePortal = () => {
    setVisible((current) => !current);
  };

  return (
    <page>
      <view className="App">
        <text className="Title">createPortal</text>

        <view className="Section">
          <text className="Label">Source</text>
          <view className="Button" bindtap={togglePortal}>
            <text className="ButtonText">{visible ? "Hide portal" : "Show portal"}</text>
          </view>
          {portalHost && visible
            ? (createPortal(
              <view className="PortalContent">
                <text className="PortalText">Rendered with createPortal</text>
              </view>,
              portalHost,
            ) as unknown as ReactNode)
            : null}
        </view>

        <view className="Section">
          <text className="Label">Target</text>
          <view className="PortalHost" ref={setPortalHost} />
        </view>
      </view>
    </page>
  );
}

root.render(<CreatePortalExample />);

```

v0.2.0


