在编辑器状态中选择特定文本

joh*_*pin 5 javascript typescript reactjs draftjs

我正在使用Draftjs创建一个富文本编辑器。这是最小的代码和框,以便您了解问题所在。

所以我有一个辅助函数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;
};
Run Code Online (Sandbox Code Playgroud)

当我在文本编辑器外部单击时,焦点会丢失,因此不会选择文本(但保留 的选定文本editorState)。

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

mzu*_*lch 3

我相信您想要做的是将焦点恢复到编辑器上。如果您所做的只是在编辑器外部单击,则选择状态不会更改(这就是您选择的文本保持不变的原因)。如果您随后恢复焦点,相同的选择将再次可见,而不会对 进行任何更改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()
};
Run Code Online (Sandbox Code Playgroud)

然后将 ref 连接到组件并将单击处理程序添加到按钮:

<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>
Run Code Online (Sandbox Code Playgroud)

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