从 HTML 设置编辑器

Sha*_*ore 0 lexicaljs

我希望用 Lexical 替换现有的 HTML 编辑器。我使用网站上的代码将 HTML 转换为节点作为起点。

https://lexical.dev/docs/concepts/serialization

正在转换数据并生成节点。

但是插入节点的时候出现如下错误?

错误:insertNode:topLevelElement 是 RangeSelection.insertNodes 处的根节点 (c:\Projects\ActivateV8\Activate.React.Web\ClientApp\node_modules\lexical\Lexical.dev.js:4002:1)

function SetDataPlugin ({model}) {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    if(!model) return;
      
    editor.update(() => {
      // In the browser you can use the native DOMParser API to parse the HTML string.
      const parser = new DOMParser();
      const dom = parser.parseFromString(model, "text/html");
      
      // Once you have the DOM instance it's easy to generate LexicalNodes.
      const nodes = $generateNodesFromDOM(editor, dom);
      
      // Select the root
      $getRoot().select();
    
      // Insert them at a selection.
      const selection = $getSelection();
      selection.insertNodes(nodes);
    });
  }, [editor,model]);
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。

Sha*_*ore 5

使用以下代码可以正常工作

  editor.update(() => {
      // In the browser you can use the native DOMParser API to parse the HTML string.
      const parser = new DOMParser();
      const dom = parser.parseFromString(model, "text/html");
      
      // Once you have the DOM instance it's easy to generate LexicalNodes.
      const nodes = $generateNodesFromDOM(editor, dom);
      
      // Select the root
      const root = $getRoot()

      const paragraphNode = $createParagraphNode();

      nodes.forEach((n)=> paragraphNode.append(n))
     
      root.append(paragraphNode);
    });
Run Code Online (Sandbox Code Playgroud)

  • 添加了 `root.getFirstDescendant()?.remove()` 以删除渲染时添加的空白节点 (2认同)