【问题标题】:Unable to set cursor in Draft.js editor无法在 Draft.js 编辑器中设置光标
【发布时间】:2016-08-03 15:37:50
【问题描述】:

我正在尝试将 Draft.js 编辑器集成到项目中。 我想使用它的方式是,在每次渲染调用时从我自己的状态中创建一个新的 EditorState(这种方法的原因与我的具体上下文有关,我不在这里详细说明)。

我没有成功的是在编辑器中设置光标位置。

我在 Codepen 上创建了一个示例: http://codepen.io/nutrina/pen/JKaaOo?editors=0011

在此示例中,我键入的任何字符都添加到文本的开头,而不是插入到光标位置。 我尝试使用以下方法设置光标:

  state = EditorState.acceptSelection(state, this.state.selectionState);
  state = EditorState.forceSelection(state, this.state.selectionState);

但没有太大的成功。 任何帮助将不胜感激。

谢谢, 杰拉德

【问题讨论】:

  • 我碰巧回答了同样的问题:stackoverflow.com/questions/38749474/…
  • @JiangYD:谢谢你的提示,我现在更进一步了。但是在我的情况下,键保持不变。我基本上是在每次渲染时恢复编辑器的选择状态,但是现在光标前进了 2 个位置?我已经更新了 Codepen 示例。有什么想法吗?
  • 我想一些按键触发了多个“onChange”事件,但是你的代码通过生成一个新的 EditorState 来破坏这些事件,然后发生了一些奇怪的事情。我认为“每次渲染调用都创建一个新的 EditorState”是行不通的。也许您可以在组件状态中设置一个 EditorState 以进行选择更改渲染,并使用您的“新状态”进行内容更改渲染。

标签: draftjs


【解决方案1】:

移动光标的简单方法是使用Editor.forceSelectionkey binding function

这就是你的渲染函数设置后的样子

render() {
    return (
      <Editor
        editorState={this.state.editorState}
        onChange={this.onChange}
        handleKeyCommand={this.handleKeyCommand}
        keyBindingFn={this.myKeyBindingFn}
      />
    );
  }

一旦你有你的键绑定功能,你可以做一些类似的事情

  myKeyBindingFn = (e) => {
    // on spacebar
    if (e.keyCode == 32) {
      const newSelection = selectionState.merge({
        anchorOffset: selectionState.getAnchorOffset() + 1,
        focusOffset: selectionState.getAnchorOffset() + 1,
      });

      const newEditorState = EditorState.forceSelection(
        editorState,
        newSelection,
      );

      this.setState({ editorState: newEditorState });

      return 'space-press';
    }
  };

随意将anchorOffsetfocusOffset 替换为您希望光标所在的位置。使用键绑定功能可以更好地控制事件

你的 handleKeyCommand 函数看起来像这样

handleKeyCommand = (command: string): DraftHandleValue => {
    if (command === 'space-press') {
      return 'handled';
    }
    return 'not-handled';
  };

【讨论】:

    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多