Skip to Content
文档

代码块

用于显示和高亮动态代码块

SourceStorybookRecipe
<div class="container">
  <h1>Hello, world!</h1>
</div>

用法

¥Usage

import { CodeBlock } from "@chakra-ui/react"
<CodeBlock.AdapterProvider>
  <CodeBlock.Root>
    <CodeBlock.Header>
      <CodeBlock.Title />
      <CodeBlock.Control>
        <CodeBlock.CopyTrigger />
        <CodeBlock.CollapseTrigger />
      </CodeBlock.Control>
    </CodeBlock.Header>
    <CodeBlock.Content>
      <CodeBlock.Code>
        <CodeBlock.CodeText />
      </CodeBlock.Code>
    </CodeBlock.Content>
  </CodeBlock.Root>
</CodeBlock.AdapterProvider>

适配器

¥Adapters

CodeBlock 组件适用于 ShikiHighlight.js 高亮引擎。

¥The CodeBlock component works for Shiki and Highlight.js highlighting engines.

文档默认使用 Shiki。

要设置代码块组件,你需要:

¥To setup the code block component, you need to:

  • 配置你首选的适配器(Shiki 或 Highlight.js)。

  • 在顶层提供 CodeBlock.AdapterProvider 的适配器。

  • CodeBlock.AdapterProvider 中渲染 CodeBlock.Root 组件。

Shiki

安装 shiki 软件包。

¥Install the shiki package.

npm install shiki

然后,创建用于动态加载所选语言的 shiki 高亮器的 shiki 适配器。

¥Then, create the shiki adapter that dynamically loads the shiki highlighter for the selected languages.

import type { HighlighterGeneric } from "shiki"
import { createShikiAdapter } from "@chakra-ui/react"

const shikiAdapter = createShikiAdapter<HighlighterGeneric<any, any>>({
  async load() {
    const { createHighlighter } = await import("shiki")
    return createHighlighter({
      langs: ["tsx", "json"],
      themes: ["github-dark", "github-light"],
    })
  },
})

<CodeBlock.AdapterProvider value={shikiAdapter}>
  {/* ... */}
</CodeBlock.AdapterProvider>

Highlight.js

安装 highlight.js 软件包。

¥Install the highlight.js package.

npm install highlight.js

然后,创建用于动态加载所选语言的 hightlight.js 适配器。

¥Then, create the highlight.js adapter that dynamically loads the selected languages.

import { createHighlightJsAdapter } from "@chakra-ui/react"
import hljs from "highlight.js/lib/core"

const highlightJsAdapter = createHighlightJsAdapter<typeof hljs>({
  async load() {
    const languages = {
      tsx: () => import("highlight.js/lib/languages/typescript"),
      html: () => import("highlight.js/lib/languages/xml"),
    }
    await Promise.all(
      Object.entries(languages).map(async ([language, file]) => {
        const { default: langModule } = await file()
        hljs.registerLanguage(language, langModule)
      }),
    )
    return hljs
  },
})

示例

¥Examples

尺寸

¥Sizes

使用 size 属性更改代码块组件的大小。

¥Use the size prop to change the size of the code block component.

(size=sm)
<div class="container">
  <h1>Hello, world!</h1>
</div>
(size=md)
<div class="container">
  <h1>Hello, world!</h1>
</div>
(size=lg)
<div class="container">
  <h1>Hello, world!</h1>
</div>

标题

¥Title

CodeBlock.Header 组件中渲染 CodeBlock.Title 组件,为代码块组件添加标题。

¥Render the CodeBlock.Title component within the CodeBlock.Header component to add a title to the code block component.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

复制按钮

¥Copy button

使用 copyButton 属性向代码块组件添加复制按钮。

¥Use the copyButton prop to add a copy button to the code block component.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

行号

¥Line numbers

行号使引用特定代码行更加容易。传递 meta.showLineNumbers 属性以在代码块组件中显示行号。

¥Line numbers make it easier to reference specific lines of code. Pass the meta.showLineNumbers prop to show line numbers in the code block component.

<div class="container">
  <h1>Hello, world!</h1>
</div>

线条高亮

¥Line highlighting

meta.highlightLines 属性传递给 CodeBlock.Root 组件,以高亮显示特定代码行。该属性接受一个行号数组。

¥Pass the meta.highlightLines prop to the CodeBlock.Root component to highlight specific lines of code. The prop accepts an array of line numbers.

<div class="container">
  <h1>Hello, world!</h1>
</div>

线条焦点

¥Line focus

meta.highlightLines 属性传递给 CodeBlock.Root 组件,以高亮显示特定代码行。该属性接受一个行号数组。行号从 1 开始。

¥Pass the meta.highlightLines prop to the CodeBlock.Root component to highlight specific lines of code. The prop accepts an array of line numbers. The line numbers are 1-based.

const greeting = "Hello, World!"

function sayHello() {
  console.log(greeting);
}

sayHello()

差异

¥Diff

差异有助于高亮源代码更改。使用 meta.addedLineNumbersmeta.removedLineNumbers 属性为代码块组件添加行号。

¥Diffs are useful for highlighting source code changes. Use the meta.addedLineNumbers and meta.removedLineNumbers props to add line numbers to the code block component.

该属性接受一个行号数组。行号从 1 开始。

const greeting = "Hello, World!"; 
function sayHello() {
  console.log("Hello, World!"); 
  console.log(greeting); 
}
sayHello();

最大行数

¥Max lines

使用 meta.maxLines 属性限制代码块组件中的行数。默认情况下,代码块组件将扩展以适应内容。

¥Use the meta.maxLines prop to limit the number of lines in the code block component. By default, the code block component will expand to fit the content.

index.tsx

语言切换器

¥Language switcher

这是一个通过组合 CodeBlockSelect 组件重新创建 API 端点请求组件的示例。

¥Here's an example that re-creates an API endpoint request component by composing the CodeBlock and Select components.

POST/v1/search
from github import Github

# Create a Github instance using an access token
g = Github("YOUR_ACCESS_TOKEN")

# Get a repository
repo = g.get_repo("octocat/Hello-World")

# Get repository information
print(f"Repository: {repo.name}")
print(f"Description: {repo.description}")
print(f"Stars: {repo.stargazers_count}")

# List issues
issues = repo.get_issues(state='open')
for issue in issues:
    print(f"Issue #{issue.number}: {issue.title}")

浮动复制按钮

¥Floating copy button

以下是向代码块组件添加浮动复制按钮的示例。

¥Here's an example that adds a floating copy button to the code block component.

<div class="container">
  <h1>Hello, world!</h1>
</div>

标签

¥Tabs

以下是将 CodeBlock 组件与 Tabs 组件组合以创建带有标签的代码块的示例。

¥Here's an example that composes the CodeBlock component with the Tabs component to create a code block with tabs.

print('Hello, World!')

标签同步

¥Tabs sync

以下是自动同步所有共享相同存储键的代码块的示例。用于文档站点中的包管理器或框架特定的代码块。

¥Here's an example that automatically syncs all code blocks that share the same storage key. Useful for package manager or framework specific code blocks in a documentation site.

npm install @chakra-ui/react
npm install @chakra-ui/react

主题

¥Themes

使用 meta.colorScheme 属性为代码块组件添加主题。在此示例中,colorScheme 已从 useColorMode 钩子设置为颜色模式。

¥Use the meta.colorScheme prop to add a theme to the code block component. In this example, the colorScheme is set to color mode from the useColorMode hook.

Loading...

溢出换行

¥Wrap overflow

使用 meta.wordWrap 属性封装代码块组件。

¥Use the meta.wordWrap prop to wrap the code block component.

index.tsx
const greeting = "Hello, World! I am a long line of text that will wrap to the next line."

function sayHello() {
  console.log(greeting)
}

sayHello()

Highlight.js

这是一个使用 hightlight.js 高亮代码块的示例。

¥Here's an example that uses highlight.js to highlight the code block.

index.html
<div class="container">
  <h1>Hello, world!</h1>
</div>

纯文本

¥Plain text

代码块默认使用纯文本。要创建纯文本代码块,请删除 CodeBlock.AdapterProvider 属性。

¥The code block falls back to a plain text by default. To create a plain text code block, remove the use of CodeBlock.AdapterProvider.

$npm install @chakra-ui/react

属性

¥Props

PropDefaultType
colorPalette 'gray'
'gray' | 'red' | 'orange' | 'yellow' | 'green' | 'teal' | 'blue' | 'cyan' | 'purple' | 'pink'

The color palette of the component

variant 'subtle'
'solid' | 'subtle' | 'outline' | 'surface' | 'plain'

The variant of the component

size 'sm'
'xs' | 'sm' | 'md' | 'lg'

The size of the component

as
React.ElementType

The underlying element to render.

asChild
boolean

Use the provided child element as the default rendered element, combining their props and behavior.

For more details, read our Composition guide.

Previous

代码

Next

Em