Skip to main content

使用客户端

use client 指令指定要在客户端渲染的组件,应在创建需要客户端 JavaScript 功能的交互式用户界面 (UI) 时使用,例如状态管理、事件处理和访问浏览器 API。这是 React 功能。

¥The use client directive designates a component to be rendered on the client side and should be used when creating interactive user interfaces (UI) that require client-side JavaScript capabilities, such as state management, event handling, and access to browser APIs. This is a React feature.

用法

¥Usage

要将组件指定为客户端组件,请在文件顶部的任何导入之前添加 use client 指令:

¥To designate a component as a Client Component, add the use client directive at the top of the file, before any imports:

'use client'

import { useState } from 'react'

export default function Counter() {
const [count, setCount] = useState(0)

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
)
}
'use client'

import { useState } from 'react'

export default function Counter() {
const [count, setCount] = useState(0)

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
)
}

在服务器组件中嵌套客户端组件

¥Nesting Client Components within Server Components

结合服务器和客户端组件允许你构建高性能和交互式的应用:

¥Combining Server and Client Components allows you to build applications that are both performant and interactive:

  1. 服务器组件:用于静态内容、数据获取和 SEO 友好元素。

    ¥Server Components: Use for static content, data fetching, and SEO-friendly elements.

  2. 客户端组件:用于需要状态、效果或浏览器 API 的交互元素。

    ¥Client Components: Use for interactive elements that require state, effects, or browser APIs.

  3. 组件组成:根据需要将客户端组件嵌套在服务器组件中,以明确分离服务器和客户端逻辑。

    ¥Component composition: Nest Client Components within Server Components as needed for a clear separation of server and client logic.

在以下示例中:

¥In the following example:

  • Header 是一个处理静态内容的服务器组件。

    ¥Header is a Server Component handling static content.

  • Counter 是一个客户端组件,可在页面内实现交互。

    ¥Counter is a Client Component enabling interactivity within the page.

import Header from './header'
import Counter from './counter' // This is a Client Component

export default function Page() {
return (
<div>
<Header />
<Counter />
</div>
)
}
import Header from './header'
import Counter from './counter' // This is a Client Component

export default function Page() {
return (
<div>
<Header />
<Counter />
</div>
)
}

参考

¥Reference

有关 use client 的更多信息,请参阅 React 文档

¥See the React documentation for more information on use client.