如何将Facebook Lexical编辑器设置为只读模式?
解决Lexical编辑器无法设置只读模式的问题
只给<ContentEditable>添加readOnly属性无法完全生效,因为Lexical的编辑权限由编辑器实例的内部状态控制,同时部分交互插件也会影响只读模式的表现。以下是具体修复方案:
步骤1:通过编辑器实例设置只读状态
使用useLexicalComposerContext获取编辑器实例,在组件挂载时调用editor.setReadOnly(true)来全局设置只读模式,这是Lexical官方推荐的核心方式:
import { useLexicalComposerContext, useEffect } from '@lexical/react'; // 在编辑器组件内部添加 const [editor] = useLexicalComposerContext(); useEffect(() => { // 全局设置编辑器为只读 editor.setReadOnly(true); }, [editor]);
步骤2:移除只读模式下的交互插件
只读模式下,工具栏、历史记录、自动聚焦这类交互插件无需保留,否则可能出现无效交互或状态冲突,通过条件渲染移除它们:
步骤3:同步ContentEditable的readOnly属性
将readOnly属性与编辑器的只读状态保持一致,避免出现状态不一致的问题。
修改后的完整代码示例
import { useLexicalComposerContext, useEffect } from '@lexical/react'; function YourEditorComponent({ note, onChange, isReadOnly = true }) { const [editor] = useLexicalComposerContext(); useEffect(() => { editor.setReadOnly(isReadOnly); }, [editor, isReadOnly]); return ( <LexicalComposer initialConfig={editorConfig}> <div className="editor-container"> {/* 只读模式下隐藏工具栏 */} {!isReadOnly && <ToolbarPlugin />} <div className="editor-inner"> <RichTextPlugin contentEditable={ <ContentEditable readOnly={isReadOnly} className="editor-input" /> } placeholder={<Placeholder />} /> {/* 只读模式下移除历史插件 */} {!isReadOnly && <HistoryPlugin />} {/* <TreeViewPlugin /> */} {/* 只读模式下移除自动聚焦插件 */} {!isReadOnly && <AutoFocusPlugin />} <CodeHighlightPlugin /> <ListPlugin /> <LinkPlugin /> <AutoLinkPlugin /> <ListMaxIndentLevelPlugin maxDepth={7} /> {/* 只读模式下移除Markdown快捷方式插件 */} {!isReadOnly && <MarkdownShortcutPlugin transformers={TRANSFORMERS} />} </div> </div> {/* 只读模式下不需要监听内容变更 */} {!isReadOnly && ( <OnChangePlugin onChange={onChange} ignoreSelectionChange ignoreHistoryMergeTagChange /> )} <TextLoader note={note} /> </LexicalComposer> ); }
额外说明
- 如果需要动态切换只读/编辑模式,只需修改
isReadOnly变量的值,编辑器实例和ContentEditable会自动同步状态。 - 检查
editorConfig,避免显式设置editable: true覆盖只读状态(默认值为true,但显式配置可能干扰只读设置)。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

