新一代富文本编辑器框架 Lexical 入门教程

简介

Lexical 是由 Facebook 开发的开源文本编辑器框架,旨在提供高性能、可扩展和灵活的文本编辑解决方案。其模块化设计和与 React 的紧密集成,使得 Lexical 成为创建现代 Web 应用中富文本编辑器的理想选择。

本教程将引导你从零开始,逐步了解并掌握 Lexical 编辑器的基本使用方法。

环境设置

在开始使用 Lexical 之前,你需要确保你的开发环境中已经安装了 Node.js 和 npm。然后按照以下步骤创建一个新的 React 项目,并安装 Lexical 相关的依赖。

1. 创建 React 项目

首先,使用 Create React App 创建一个新的 React 项目:

npx create-react-app lexical-editor
cd lexical-editor

2. 安装 Lexical 依赖

接下来,安装 Lexical 和相关的依赖包:

npm install @lexical/react @lexical/rich-text

基本使用

在安装完必要的依赖后,我们可以开始在项目中使用 Lexical。

1. 设置基础编辑器

在 src 目录下创建一个新的组件 LexicalEditor.js,并在其中设置一个最基本的 Lexical 编辑器。

// src/LexicalEditor.js
import React from 'react';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';

const editorConfig = {
  namespace: 'MyEditor',
  theme: {
    // Customize your theme here
    text: {
      bold: 'text-bold',
      italic: 'text-italic',
    },
  },
  onError(error) {
    console.error('Lexical error:', error);
  },
};

function LexicalEditor() {
  return (
    <LexicalComposer initialConfig={editorConfig}>
      <div className="editor-container">
        <RichTextPlugin
          contentEditable={<ContentEditable className="editor" />}
          placeholder={<div className="placeholder">Enter some text...</div>}
          ErrorBoundary={LexicalErrorBoundary}
        />
        <HistoryPlugin />
        <OnChangePlugin
          onChange={(editorState) => {
            editorState.read(() => {
              // Read the contents of the EditorState here.
              console.log('Editor state changed');
            });
          }}
        />
      </div>
    </LexicalComposer>
  );
}

export default LexicalEditor;

2. 在应用中使用编辑器

修改 src/App.js,将 LexicalEditor 组件引入并渲染:

// src/App.js
import React from 'react';
import './App.css';
import LexicalEditor from './LexicalEditor';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>Lexical Editor Example</h1>
      </header>
      <main>
        <LexicalEditor />
      </main>
    </div>
  );
}

export default App;

3. 添加样式

在 src/App.css 文件中添加一些基本样式:

/* src/App.css */
.App {
  text-align: center;
}

.App-header {
  background-color: #282c34;
  padding: 20px;
  color: white;
}

.editor-container {
  margin: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.editor {
  min-height: 200px;
  outline: none;
}

.placeholder {
  color: #888;
  position: absolute;
  pointer-events: none;
  user-select: none;
}

4. 运行应用

完成上述步骤后,运行以下命令启动开发服务器:

npm start

打开浏览器访问 http://localhost:3000,你将看到一个简单的 Lexical 富文本编辑器。

高级功能

Lexical 提供了许多插件和扩展功能,允许你根据需求定制编辑器。以下是一些常用的高级功能:

1. 添加工具栏

工具栏可以提供基本的文本格式化功能,例如加粗、斜体等。你可以创建一个简单的工具栏组件并将其集成到编辑器中。

// src/Toolbar.js
import React from 'react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { $getSelection, $isRangeSelection, FORMAT_TEXT_COMMAND } from 'lexical';

function Toolbar() {
  const [editor] = useLexicalComposerContext();

  const formatText = (command) => {
    editor.update(() => {
      const selection = $getSelection();
      if ($isRangeSelection(selection)) {
        editor.dispatchCommand(FORMAT_TEXT_COMMAND, command);
      }
    });
  };

  return (
    <div className="toolbar">
      <button onClick={() => formatText('bold')}>Bold</button>
      <button onClick={() => formatText('italic')}>Italic</button>
    </div>
  );
}

export default Toolbar;

将工具栏添加到 LexicalEditor 组件中:

// src/LexicalEditor.js
import Toolbar from './Toolbar';

function LexicalEditor() {
  return (
    <LexicalComposer initialConfig={editorConfig}>
      <div className="editor-container">
        <Toolbar />
        <RichTextPlugin
          contentEditable={<ContentEditable className="editor" />}
          placeholder={<div className="placeholder">Enter some text...</div>}
          ErrorBoundary={LexicalErrorBoundary}
        />
        <HistoryPlugin />
        <OnChangePlugin
          onChange={(editorState) => {
            editorState.read(() => {
              // Read the contents of the EditorState here.
              console.log('Editor state changed');
            });
          }}
        />
      </div>
    </LexicalComposer>
  );
}

2. 支持协作编辑

Lexical 支持多用户实时协作编辑。你可以使用 @lexical/yjs 插件集成 Yjs(一个高效的实时协作编辑库)。

首先,安装相关依赖:

npm install yjs @lexical/yjs

然后,在 LexicalEditor 组件中添加协作插件:

import { CollaborationPlugin } from '@lexical/yjs';
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';

const doc = new Y.Doc();
const provider = new WebsocketProvider('ws://localhost:1234', 'lexical', doc);

function LexicalEditor() {
  return (
    <LexicalComposer initialConfig={editorConfig}>
      <div className="editor-container">
        <Toolbar />
        <RichTextPlugin
          contentEditable={<ContentEditable className="editor" />}
          placeholder={<div className="placeholder">Enter some text...</div>}
          ErrorBoundary={LexicalErrorBoundary}
        />
        <CollaborationPlugin
          id="collab-editor"
          provider={provider}
          doc={doc}
        />
        <HistoryPlugin />
        <OnChangePlugin
          onChange={(editorState) => {
            editorState.read(() => {
              // Read the contents of the EditorState here.
              console.log('Editor state changed');
            });
          }}
        />
      </div>
    </LexicalComposer>
  );
}

总结

通过本教程,你已经学习了如何在 React 项目中集成和使用 Lexical 编辑器。从基本配置到添加工具栏和协作功能,Lexical 为开发者提供了创建高性能、可扩展富文本编辑器的强大工具。根据需要,深入了解 Lexical 的更多插件和扩展,进一步提升你的编辑器功能。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乌南竹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值