# 文本对齐 {#text-align}

Source: [在 React 编辑器中设置文本对齐 · Yurich](https://leeyujoo.com/yurich/zh-cn/features/text-align/)

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

Package version: `0.1.2`

调整段落和列表项的对齐方式。

## 试一试 {#try-it}

在示例段落中点击 **居中**。HTML 包含 `style="text-align: center"`，JSON 中的 `attrs.textAlign` 为 `"center"`。

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

启用 `TextAlign` 并分别连接左、中、右和两端对齐命令。

```tsx
import {
  EditorContent, EditorProvider, TextAlign, useEditor, useIsActive,
  type EditorInstance,
} from 'yurich';

const choices = [
  ['alignLeft', "左对齐"],
  ['alignCenter', "居中"],
  ['alignRight', "右对齐"],
  ['alignJustify', "两端对齐"],
] as const;

function AlignButton({ editor, command, label }: {
  editor: EditorInstance;
  command: (typeof choices)[number][0];
  label: string;
}) {
  const active = useIsActive(editor, command);

  return (
    <button
      type="button"
      aria-pressed={active}
      onMouseDown={event => event.preventDefault()}
      onClick={() => editor.execute(command)}
    >
      {label}
    </button>
  );
}

export function AlignmentEditor() {
  const editor = useEditor({
    extensions: [TextAlign],
    initialValue: "<p>现在轮到工具栏发言了。</p>",
  });

  return (
    <EditorProvider editor={editor}>
      <div role="group" aria-label="文本对齐">
        {choices.map(([command, label]) => (
          <AlignButton key={command} editor={editor} command={command} label={label} />
        ))}
      </div>
      <EditorContent ariaLabel="编辑器" />
    </EditorProvider>
  );
}
```

## 行为说明 {#behavior}

命令可作用于多个选中的块。载入保存的内容时也要启用 `TextAlign`。

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