如何在 Next 13.4 中创建门户/模式

Re9*_*Nee 10 modal-dialog reactjs next.js react-portal

我想在 NextJS 13.4 中创建一个 Modal(使用新的layout.tsx 文件系统),但我做不到。由于这是一个新事物,我在网上也找不到解决方案。

以下是我尝试过的事情:

编辑

  1. 在解决方案中:
import React from "react";
import { createPortal } from "react-dom";

const Modal = () => {
    return createPortal(
        <React.Fragment>
            <div>your content</div>
        </React.Fragment>,
        Document.body as HTMLElement
    );
};

export default Modal;
Run Code Online (Sandbox Code Playgroud)

它会抛出:

文档未定义

尝试从“next/document”导入文档,但仍然无法正常工作。

另一个错误是error Error: createPortal was called on the server. Portals are not currently supported on the server. Update your program to conditionally call createPortal on the client only.

我在第一行添加了“使用客户端”,它将解决该错误。

但仍然没有显示模态内容的结果。

  1. 如何在 Next Js 中创建门户

由于本教程的第 1 步是创建一个 _document 文件并在其中放置具有特定 ID 的门户元素,因此我在 Layout.tsx 中执行了此操作(我认为它与文档文件相同)。

布局.tsx 代码

结果是:水合错误

  1. 其他教程也得到了同样的结果......

请提供有效答案。我知道如何在 React 或 Next 的早期版本中创建门户。这是一个新版本,改动不大。

Igo*_*nko 14

您可以Modal通过两个简单的步骤使您的组件与 Next.js 13 应用程序路由器兼容:

  1. 通过添加注释将您声明Modal为客户端组件"use client"

  2. 仅当组件已安装在客户端上时才渲染其子组件。

"use client";

import * as React from "react";
import { createPortal } from "react-dom";

export default function Modal({ children }: React.PropsWithChildren) {
  const [mounted, setMounted] = React.useState(false);

  React.useEffect(() => setMounted(true), []);

  return mounted ? createPortal(<>{children}</>, document.body) : null;
}
Run Code Online (Sandbox Code Playgroud)