# 链接 {#link}

Source: [在 React 编辑器中添加和移除链接 · Yurich](https://leeyujoo.com/yurich/zh-cn/features/link/)

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

Package version: `0.1.2`

为选中文字或光标处添加链接。

## 试一试 {#try-it}

选中 “格式指南”，点击 **添加链接** 并输入 `https://example.com`。把光标放进链接后，点击 **移除链接** 来移除链接。

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

启用 `Link`，调用 `editor.execute('setLink', { href })`。示例打开 URL 输入框并保留选区。

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

export function LinkEditor() {
  const editor = useEditor({
    extensions: [Link],
    initialValue: "<p>把按钮都点一遍之前，先读读格式指南。</p>",
  });
  const active = useIsActive(editor, 'link');

  function addLink() {
    const href = window.prompt("链接地址", 'https://example.com');
    if (href) editor.execute('setLink', { href });
  }

  return (
    <EditorProvider editor={editor}>
      <div role="group" aria-label="链接">
        <button
          type="button"
          onMouseDown={event => event.preventDefault()}
          onClick={addLink}
        >
          添加链接
        </button>
        <button
          type="button"
          disabled={!active}
          onMouseDown={event => event.preventDefault()}
          onClick={() => editor.execute('removeLink')}
        >
          移除链接
        </button>
      </div>
      <EditorContent ariaLabel="编辑器" />
    </EditorProvider>
  );
}
```

## 行为说明 {#behavior}

支持 `http://`、`https://` 和 `mailto:`。没有选区时，URL 本身是显示的链接文字。

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