gpt4 book ai didi

draftjs - 无法在 Draft.js 编辑器中设置光标

转载 作者:行者123 更新时间:2023-12-02 10:25:33 27 4
gpt4 key购买 nike

我正在尝试将 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);

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

谢谢,杰拉德

最佳答案

移动光标的一个简单方法是使用 Editor.forceSelection和一个key binding function !

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

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

一旦你有了按键绑定(bind)功能,你就可以按照以下方式做一些事情

  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 替换为您希望光标所在的位置。使用键绑定(bind)功能可以更好地控制事件

你的handleKeyCommand函数看起来像这样

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

关于draftjs - 无法在 Draft.js 编辑器中设置光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38748053/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com