javascript - 在 editorState 中选择特定文本

标签 javascript reactjs typescript draftjs

我正在使用 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()
};
然后将 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>
完整示例:https://codesandbox.io/s/flamboyant-hill-l31bn

关于javascript - 在 editorState 中选择特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63519242/

相关文章:

javascript - Node 服务器的 HTTPRequest 在 IE 8 中工作,但在 IE 7 中不起作用

javascript - 从 HTML5 input[type ="date"] in chrome 获取输入值

javascript - React onChange 不适用于功能组件内的输入

typescript - 如何以编程方式在 Typescript 中创建类函数?

reactjs - CRA 忽略 jest.config 文件

javascript - 正则表达式 '\s+-\s*|\s*-\s+' 无法正常工作

javascript - cURL 命令有效,但 Fetch API 调用返回 200,响应负载中出现 400 验证错误

javascript - react 最终形式我只想在所有字段都有效的情况下处理提交

javascript - 如何让我的表情符号在 emoji-mart 中看起来更漂亮?

angular - 组件重定向后保持 Angular Material 表状态