solid js - How to modify the internal state of a Lexical editor from outside the editor? - Stack Overflow

admin2025-04-22  2

I'm working on a project where I'm implementing Lexical as part of a text editor. However, Lexical is used for multiple cells at once. My TranslationEditor component looks like this:

const TranslationEditor = (props) => {
  return (
    <LexicalComposer
      initialConfig={...}
    >
      <RichTextPlugin
        contentEditable={
          <ContentEditable
            ref={props.ref}
            data-node="translation"
            data-segment-id={props.id}
          />
        }
      />
    </LexicalComposer>
  )
}

I want to programmatically manipulate the nodes inside the editor. I'm trying to access the editor content via querySelector and perform DOM manipulations directly. Here are the scenarios I've encountered:

What works: Adding/removing classes or modifying attributes of nodes inside Lexical using standard DOM methods like element.classList.remove('test') works as expected.

What doesn't work: When I attempt to replace, remove, or add nodes using DOM methods, such as node.replaceWith(...newNodes), the changes have no effect. Lexical doesn't update its content, and no errors are thrown. Here's an example:

function spellcheckNode() {
  const translationNode = document.querySelector(`[data-node="translation"][data-segment-id=[...]`)
  const regexp = new RegExp(...);
  //
  [..translationNode.firstElementChild.childNodes].forEach((node) => {

    const textTokens = node.textContent.split(regexp).filter(Boolean);
    const newNodes = textTokens.map((text) => {
      if (misspelled.has(text)) {
        const span = document.createElement('span');
        span.textContent = text;
        span.classList.add('misspelled');
        return span;
      } else {
        return document.createTextNode(text);
      }
    });

    node.replaceWith(...newNodes);
  });
}

Is it possible to somehow change the internal state of editors from the outside using DOM manipulations or is there another way to access the editor from the outside?

转载请注明原文地址:http://anycun.com/QandA/1745302850a90602.html