---
title: "添加按钮以更改文本对齐"
description: "使用这个按钮 UI 组件在 Tiptap 编辑器中更改文本对齐方式。更多内容请查看文档！"
canonical_url: "https://tiptap.zhcndoc.com/ui-components/components/text-align-button"
---

# 添加按钮以更改文本对齐

使用这个按钮 UI 组件在 Tiptap 编辑器中更改文本对齐方式。更多内容请查看文档！

使用这个按钮 UI 组件在 Tiptap 编辑器中更改文本对齐方式。

> **Interactive demo:** [text align button](https://template.tiptap.dev/preview/tiptap-ui/text-align-button)

## 安装

您可以通过 Tiptap CLI（适用于 Vite 或 Next.js）添加该组件。

```bash
npx @tiptap/cli@latest add text-align-button
```

### 手动集成

对于除了 Vite 或 Next.js 之外的框架，请从 [开源库](https://github.com/ueberdosis/tiptap-ui-components/tree/main/apps/web/src/components/tiptap-ui/text-align-button) 手动添加组件。

### 导入样式

此组件需要您导入我们的样式，这些样式已添加到 `styles/keyframe-animation.scss` 和 `styles/_variables.scss`。

## 用法

```tsx
import { EditorContent, EditorContext, useEditor } from '@tiptap/react'
import { StarterKit } from '@tiptap/starter-kit'
import { TextAlign } from '@tiptap/extension-text-align'
import { TextAlignButton } from '@/components/tiptap-ui/text-align-button'

import '@/components/tiptap-node/paragraph-node/paragraph-node.scss'

export default function MyEditor() {
  const editor = useEditor({
    immediatelyRender: false,
    extensions: [StarterKit, TextAlign.configure({ types: ['heading', 'paragraph'] })],
    content: `
        <p>尝试选择一个段落并点击其中一个文本对齐按钮。</p>
        <p style="text-align: left">左对齐文本。</p>
        <p style="text-align: center">中间对齐文本。</p>
        <p style="text-align: right">右对齐文本。</p>
        <p style="text-align: justify">两端对齐文本。</p>
        `,
  })

  return (
    <EditorContext.Provider value={{ editor }}>
      <TextAlignButton
        editor={editor}
        align="left"
        text="Left"
        hideWhenUnavailable={true}
        showShortcut={true}
        onAligned={() => console.log('Text aligned!')}
      />
      <TextAlignButton align="center" />
      <TextAlignButton align="right" />
      <TextAlignButton align="justify" />

      <EditorContent editor={editor} role="presentation" />
    </EditorContext.Provider>
  )
}
```

#### 属性

| 名称                  | 类型                                         | 默认    | 描述            |
| ------------------- | ------------------------------------------ | ----- | ------------- |
| editor              | Editor \| null                             | null  | Tiptap 编辑器实例  |
| align               | 'left' \| 'center' \| 'right' \| 'justify' | 必需    | 要应用的文本对齐方式    |
| hideWhenUnavailable | boolean                                    | false | 如果不可用，按钮是否应隐藏 |
| text                | string                                     | -     | 显示在图标旁的文本     |

#### 要求

使用的参考组件

- `use-tiptap-editor`（钩子）
- `button`（原语）
- `align-left-icon`（图标）
- `align-right-icon`（图标）
- `align-center-icon`（图标）
- `align-justify-icon`（图标）

开源功能

- `@tiptap/extension-text-align`
