Lexical 概念

2024-09-05  本文已影响0人  欢欣的膜笛

介绍

主要概念

Editor instances

Editor States

Editor Updates

DOM Reconciler

Listeners, Node Transforms and Commands

const unregisterListener = editor.registerUpdateListener(({editorState}) => {
  // An update has occurred!
  console.log(editorState);
});

// Ensure we remove the listener later!
unregisterListener();

如何独立于任何框架或库使用 Lexical

Creating an editor and using it

import {createEditor} from 'lexical';

// 创建编辑器实例
const config = {
  namespace: 'MyEditor',
  theme: {
    ...
  },
  onError: console.error
};
const editor = createEditor(config);

// 将编辑器实例与 a content editable <div> element 关联起来
const contentEditableElement = document.getElementById('editor');
editor.setRootElement(contentEditableElement);

// 从元素中清除编辑器实例
// editor.setRootElement(null)

Working with Editor States

const stringifiedEditorState = JSON.stringify(editor.getEditorState().toJSON());
const newEditorState = editor.parseEditorState(stringifiedEditorState);

Updating an editor

有几种方法可以更新编辑器实例(异步过程):

import {$getRoot, $getSelection, $createParagraphNode, $createTextNode} from 'lexical';

// Inside the `editor.update` you can use special $ prefixed helper functions.
// These functions cannot be used outside the closure, and will error if you try.
// (If you're familiar with React, you can imagine these to be a bit like using a hook
// outside of a React function component).
editor.update(() => {
  // Get the RootNode from the EditorState
  const root = $getRoot();

  // Get the selection from the EditorState
  const selection = $getSelection();

  // Create a new ParagraphNode
  const paragraphNode = $createParagraphNode();

  // Create a new TextNode
  const textNode = $createTextNode('Hello world');

  // Append the text node to the paragraph
  paragraphNode.append(textNode);

  // Finally, append the paragraph to the root
  root.append(paragraphNode);
});

如果您想知道编辑器何时更新以便对更改做出反应,可以向编辑器添加更新侦听器,如下所示:

editor.registerUpdateListener(({editorState}) => {
  // The latest EditorState can be found as `editorState`.
  // To read the contents of the EditorState, use the following API:

  editorState.read(() => {
    // Just like editor.update(), .read() expects a closure where you can use
    // the $ prefixed helper functions.
  });
});
上一篇 下一篇

猜你喜欢

热点阅读