Client Component 在浏览器中运行(也会在服务器上为初始 HTML 进行预渲染)。您可以在文件顶部使用 "use client" 指令选择加入。当您需要交互性、state、effects 或 browser APIs 时,您就需要它们。
声明一个
tsx
;
{ useState } ;
() {
[count, setCount] = ();
;
}
✓ useState / useReducer / useEffect / useRef / useContext
✓ Event handlers (onClick, onChange, onSubmit)
✓ Browser APIs (window, localStorage, navigator, IntersectionObserver)
✓ Third-party libraries that use any of the above (most UI/animation libs)
将文件标记为 "use client" 会使它和它导入的所有内容成为 client bundle 的一部分。因此,您希望 client 边界小且低于树中 — "client islands" — 而不是将顶级 layout 标记为 client(这会将整个应用拉入浏览器 bundle)。
// ✅ Good: server page, small client island only where needed
export default async function Page() { // Server Component
const data = await getData();
return <><StaticContent data={data} /><InteractiveWidget /></>; // island is "use client"
}
// Server Component fetches, passes serializable props down to the client island
<LikeButton initialLikes={post.likes} postId={post.id} />
从 Server 传递到 Client Component 的 Props 必须是可序列化的(没有函数、没有类实例),因为它们跨越 server→client 边界。
Client Components 是您在以服务器为主的应用中添加交互性的方式。
技巧是保持它们最小化并位于树叶处 — 在需要的地方提供交互性,其他地方使用 Server Components — 这样您可以运送最少的 JavaScript。
在树中较高的位置错误放置 "use client" 是一个常见错误,它会膨胀 bundle 并丧失 Server Components 的好处。