如何在 Lexical.js 中以编程方式选择文本范围

问题描述 投票:0回答:1

我正在尝试词汇,并且我有一个无法实现的特定用例。

用户输入一些文本,应用程序将其发送到后端以检查是否有错误。作为响应,后端返回有关包含错误的单词的指定位置的错误信息。

现在,我需要获取这些偏移量并根据它们选择文本片段。

例如。 用户输入文本:“Hello worldd!” 从后端信息得知我应该突出显示

worldd

我还没有找到如何在词汇中做到这一点。

这是我尝试过的一个例子。

editor.update(() => {
  const rangeSelection = $createRangeSelection();

  rangeSelection.applyDOMRange({
    startContainer: editor.getRootElement(),
    endContainer: editor.getRootElement(),
    collapsed: false,
    startOffset: 6,
    endOffset: 12,
  });

  $setSelection(rangeSelection);
});

// Here I'm trying to get the current selection.
const selection = $getSelection();

// The text contains the entire text in editor, but not the text I selected at previous step
const text = selection.getTextContent();

javascript reactjs lexicaljs
1个回答
0
投票

我也在寻找您问题的解决方案。抱歉有点晚了,但这是我的解决方案。

在下面的模型中,我只是将选择向前移动一个字符(锚点和焦点),但当然您可以在用例中执行您需要的任何操作。请记住这些值是相对于参数 1 和 3 中的节点而言的。

我尝试保持类型明确,以便您可以在 docs 中更轻松地找到它们。

import {
    $createRangeSelection,
    $createTextNode,
    $getSelection,
    $isRangeSelection,
    $setSelection,
    PointType,
} from "lexical";

const YourPlugin = () => {
    const [editor] = useLexicalComposerContext();

    const foo = (): boolean => {
        editor.update(() => {
            const currentSelection = $getSelection();

            // Just for this example, I'm moving the selection forward by 1 character but do whatever you need to do.
            const selectionOffset: number = 1;

            if ($isRangeSelection(currentSelection)) {
                const anchor: PointType | null = currentSelection.anchor;
                const focus: PointType | null = currentSelection.focus;

                const newNode = $createTextNode("Some new node");
                // ^^ This could also be an existing node - whatever applies to your app.

                const newSelection = $createRangeSelection();
                newSelection.setTextNodeRange(newNode, anchor.offset + selectionOffset, newNode, focus.offset + selectionOffset);
                $setSelection(newSelection);
            }
        });

        return true;
    };
}

export default YourPlugin

希望这能给你一些启发。另外,如果您需要在更新后检查选择,请记住,一般来说,名称前面带有 $ 前缀的词法函数需要在

editor.update(() => {})
editorState.read(() => {})
内调用。 IE。您应该能够将这些行移到更新回调中。

© www.soinside.com 2019 - 2024. All rights reserved.