简介
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
tex