【问题标题】:Select specific text in the editorState在 editorState 中选择特定文本
【发布时间】:2020-08-25 13:21:30
【问题描述】:

我正在使用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 中的文本就会被选中。

【问题讨论】:

    标签: javascript reactjs typescript draftjs


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答先生。可悲的是,我搞砸了我的例子,这就是答案如此明显的原因。我真正的问题是当我选择一个文本时,更改editorState,然后尝试重新选择之前的选择。我赞成您的回答,但我需要更新我的问题。很抱歉。
    • 最后,我最初的问题与.focus() 本身无关。所以你的回答真的很有帮助。
    【解决方案2】:

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

    EditorState.push( editorState, contentState, changeType)
    

    More Info

    【讨论】:

      猜你喜欢
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多