# 代码块 {#code-block}

Source: [为 React 编辑器添加代码块 · Yurich](https://leeyujoo.com/yurich/zh-cn/features/code-block/)

Package: [`yurich`](https://www.npmjs.com/package/yurich)

Package version: `0.1.2`

用独立块显示多行代码。

## 试一试 {#try-it}

在示例段落中点击 **代码块**。结果是 `<pre>editor.execute('toggleBold');</pre>`。

## 添加到编辑器 {#setup}

启用 `CodeBlock` 并调用 `toggleCodeBlock` 创建 `<pre>`。

```tsx
import { EditorContent, EditorProvider, CodeBlock, useEditor, useIsActive } from 'yurich';

export function CodeBlockEditor() {
  const editor = useEditor({
    extensions: [CodeBlock],
    initialValue: "<p>editor.execute('toggleBold');</p>",
  });
  const active = useIsActive(editor, 'toggleCodeBlock');

  return (
    <EditorProvider editor={editor}>
      <button
        type="button"
        aria-pressed={active}
        onMouseDown={event => event.preventDefault()}
        onClick={() => editor.execute('toggleCodeBlock')}
      >
        代码块
      </button>
      <EditorContent ariaLabel="编辑器" />
    </EditorProvider>
  );
}
```

## 行为说明 {#behavior}

在块中粘贴纯文本会保留换行。语法高亮可由应用提供。

[功能](https://leeyujoo.com/yurich/zh-cn/features/)
