在editorState中选择特定的文本

问题描述

我正在使用draftjs创建富文本编辑器。这是最小的codesandbox,因此您可以大致了解问题所在。

所以我有一个辅助函数getCurrentTextSelection,该函数会向我返回我选择的文本:

const getCurrentTextSelection = (editorState: EditorState): string => {
  const selectionState = editorState.getSelection();
  const anchorKey = selectionState.getAnchorKey();
  const currentContent = editorState.getCurrentContent();
  const currentContentBlock = currentContent.getBlockForKey(anchorKey);
  const start = selectionState.getStartOffset();
  const end = selectionState.getEndOffset();
  const selectedText = currentContentBlock.getText().slice(start,end);

  return selectedText;
};

当我在TextEditor之外单击时,焦点丢失,因此未选择文本(但将选中的文本留在editorState上。)

是否有编程方式使用editorState重新选择此文本?这样,当您单击Select text again按钮时,就会选择TextEditor中的文本。

解决方法

我相信您正在寻找的是将焦点恢复到编辑器上。如果您要做的就是在编辑器外部单击,则选择状态不会更改(这就是您选择的文本保持不变的原因)。如果您随后恢复焦点,则相同的选择将再次可见,而无需更改editorState

Draft.js包含一些有关如何执行此操作的文档:https://draftjs.org/docs/advanced-topics-managing-focus/

Editor组件本身具有一个focus()方法,如您所料,该方法将焦点恢复到编辑器。您可以使用ref来访问组件实例:

const editorRef = React.useRef<Editor>(null)

const selectAgain = () => {
  editorRef.current.focus()
};

然后将引用连接到组件,并将点击处理程序添加到按钮:

<div>
  <Editor
    editorState={editorState}
    onChange={onEditorStateChange}
    placeholder={placeholder}
    ref={editorRef} // added ref
  />

  <h2>Selected text:</h2>
  <p>{getCurrentTextSelection(editorState)}</p>

  // added click handler
  <button onClick={selectAgain}>Select text again</button> 
</div>

完整示例:https://codesandbox.io/s/flamboyant-hill-l31bn

,

也许您可以将selectedText存储到EditorState中 使用

EditorState.push( editorState,contentState,changeType)

More Info