发布于 2024-07-02, 更新于 2024-07-05
编写用户交互组件,以及引用 And Design 等部分第三方前端组件,都需要写在客户端组件中。可在服务端组件中嵌套客户端组件结合使用。
https://nextjs.org/docs/app/building-your-application/rendering/client-components
默认,如需使用客服端组件,可在头部声明:
"use client";
需要编写用于用户交互的组件,都需要写在客服端组件中。比如编写点击等 dom 事件逻辑,服务端组件会报错。
比如给 Next.js 引入 And Design,按照文档的方式安装:
https://ant.design/docs/react/use-with-next-cn
直接使用组件会有报错,比如调用 Footer 组件会报 Unhandled Runtime Error 错误。
可在封装一层客户端组件,来导入第三方前端组件:
"use client";
import { Layout } from "antd";
const { Footer } = Layout;
客户端组件有许多能力受到限制,比如无法导出 metadata,当有这个需要时,比如在 layout.tsx 中,则不能使用 use client。
可额外再嵌套一个客户端组件使用。
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="zh">
<body>
<CommonLayout>
{children}
</CommonLayout>
</html>
);
}
next/dynamic 是 React.lazy() 和 Suspense 的结合体,适用于客户端组件。
const ComponentA = dynamic(() => import('../components/A'))
默认情况下,客户端组件将处于预渲染状态(SSR)。如果要禁用客户端组件的预渲染,可以将 ssr 设置为 false :
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
https://nextjs.org/docs/messages/react-hydration-error
ssr: falsesuppressHydrationWarning 属性避免警告