如何在LexicalJS中使用自定义组件库替代原生DOM渲染
用自定义React组件替代Lexical提及插件的默认DOM渲染
要在Lexical的提及插件中用自定义函数组件替代原生DOM元素渲染,核心是自定义节点类+绑定React渲染组件,完全不需要依赖super.createDOM()。以下是具体实现步骤:
1. 定义自定义提及节点类
继承Lexical的TextNode(因为提及本质是文本节点),跳过createDOM方法的重写,专注节点的类型标识、克隆和序列化逻辑:
import { TextNode } from 'lexical'; export class CustomMentionNode extends TextNode { static getType() { return 'custom-mention'; } static clone(node) { return new CustomMentionNode(node.__text, node.__key); } // 序列化节点数据,用于编辑器保存/恢复 exportJSON() { return { ...super.exportJSON(), type: 'custom-mention', }; } // 反序列化,从JSON还原节点 static importJSON(serializedNode) { const node = $createCustomMentionNode(serializedNode.text); node.setFormat(serializedNode.format); node.setDetail(serializedNode.detail); return node; } } // 封装创建节点的工具函数,方便调用 export function $createCustomMentionNode(text) { return new CustomMentionNode(text); }
2. 编写自定义React函数组件
实现你想要的提及样式和交互,比如带背景色、hover效果的文本组件:
import React from 'react'; export const CustomMentionText = ({ node }) => { return ( <span className="custom-mention" style={{ backgroundColor: '#E8F3FF', padding: '2px 6px', borderRadius: '4px', color: '#165DFF', cursor: 'pointer' }} > {node.getTextContent()} </span> ); };
3. 绑定节点与React组件
在编辑器初始化时,通过Lexical React的registerReactComponent方法,将自定义节点映射到你的React组件,替代默认的DOM渲染:
import { LexicalComposer } from '@lexical/react/LexicalComposer'; import { registerReactComponent } from '@lexical/react'; import { CustomMentionNode, $createCustomMentionNode } from './CustomMentionNode'; import { CustomMentionText } from './CustomMentionText'; import { MentionsPlugin } from '@lexical/react/LexicalMentionsPlugin'; const initialConfig = { // 注册自定义节点,让编辑器识别 nodes: [CustomMentionNode], // 其他编辑器配置... }; function MyEditor() { return ( <LexicalComposer initialConfig={initialConfig}> {/* 注册节点与React组件的映射 */} <LexicalComposer.Context.Consumer> {(editor) => { registerReactComponent(CustomMentionNode.getType(), CustomMentionText); return null; }} </LexicalComposer.Context.Consumer> {/* 自定义提及插件,替换默认的节点创建逻辑 */} <MentionsPlugin // 保留原有的数据源、触发字符等配置 onSelectMention={(mention) => { // 插入自定义提及节点,而非默认的TextNode editor.update(() => { const mentionNode = $createCustomMentionNode(mention.name); $insertNodes([mentionNode]); }); }} /> {/* 其他编辑器UI组件(如RichTextPlugin、ToolbarPlugin) */} </LexicalComposer> ); } export default MyEditor;
关键说明
- 无需重写
createDOM/updateDOM:Lexical React会优先使用你注册的React组件渲染节点,跳过原生DOM创建逻辑。 - 节点类型唯一:自定义节点的
getType()返回值必须唯一,避免与内置节点冲突。 - 序列化必须实现:确保编辑器刷新或保存后,自定义节点能正确还原。
内容的提问来源于stack exchange,提问作者Asso
相关产品推荐
相关产品推荐

