Lexical编辑器设置初始文本报错:Cannot read properties of undefined (reading 'type')
Lexical编辑器设置初始文本报错:TypeError: Cannot read properties of undefined (reading 'type') 解决方法
错误原因
你传入的editorState格式完全不符合Lexical的要求:
- 你用了HTML转义后的字符串
'{"text":"sample text"}',解析后只是简单的{"text":"sample text"},但Lexical的编辑器状态要求是包含root节点层级结构的对象/JSON字符串; - Lexical无法识别这种自定义的简单结构,找不到核心的
root节点及其type属性,因此抛出Cannot read properties of undefined (reading 'type')错误。
正确解决方案
方案1:直接传入符合Lexical规范的初始状态
Lexical的编辑器状态必须包含root根节点,下面嵌套段落、文本等节点。你可以直接传入解析后的JS对象,或者合法的JSON字符串(不要HTML转义):
方式1-1:传入JS对象
const editorConfig = { editorState: { root: { type: "root", children: [ { type: "paragraph", children: [ { type: "text", text: "sample text" } ] } ], direction: "ltr" } }, // 其他配置项 };
方式1-2:传入合法JSON字符串
const editorConfig = { editorState: '{"root":{"type":"root","children":[{"type":"paragraph","children":[{"type":"text","text":"sample text"}]}],"direction":"ltr"}}', // 其他配置项 };
方案2:通过编辑器实例动态设置初始内容(更灵活)
如果不想手动编写状态结构,可以在组件挂载后,利用Lexical的API插入内容:
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; import { $getRoot, $createParagraphNode, $createTextNode } from 'lexical'; import { useEffect } from 'react'; function Placeholder() { return <div className="editor-placeholder">Enter some rich text...</div>; } const editorConfig = { // 这里不需要再写editorState // 其他配置项 }; export default function Editor() { const [editor] = useLexicalComposerContext(); useEffect(() => { editor.update(() => { const root = $getRoot(); root.clear(); // 清空默认内容 // 创建段落和文本节点 const paragraph = $createParagraphNode(); const text = $createTextNode('sample text'); paragraph.append(text); root.append(paragraph); }); }, [editor]); return ( <LexicalComposer initialConfig={editorConfig}> <div className="editor-container"> <ToolbarPlugin /> <div className="editor-inner"> <RichTextPlugin contentEditable={<ContentEditable className="editor-input" />} placeholder={<Placeholder />} /> {/* 其他组件 */} </div> </div> </LexicalComposer> ); }
内容的提问来源于stack exchange,提问作者kar
相关产品推荐
相关产品推荐

