React 富文本编辑器 - 在 ENTER 上清除状态



我想在按回车键时清除 React 富文本编辑器 (https://github.com/sstur/react-rte( 的状态。

我的状态如下所示:

state = {
value: RichTextEditor.createEmptyValue()
}

RichTextEditor组件提供句柄返回道具。因此,我实现了以下handleReturn函数:

handleReturn = () => {this.setState(prevState => ({
...prevState,
value: RichTextEditor.createValueFromString("", "html")
}));
}

当我从富文本编辑器本身之外的按钮触发句柄返回函数时,它工作正常,状态(和文本输入区域(被正确清除。但是,当从回车键触发相同的句柄返回时,它不会清除状态;但我可以看到句柄返回函数已正确触发。我将函数传递给组件,如下所示:

<RichTextEditor handleReturn={this.handleReturn} value={this.state.value}
onChange={this.onChange}/>

任何帮助,不胜感激。谢谢!

更新:我最终直接实现了底层draft.js库(https://draftjs.org/(。这是一个非常顺利的过程,它通过绕过react-rte的使用解决了这个问题。所以如果你有可能的话,建议你切换。

这可以提供帮助,有点渴望重置输入,但它有效

handleReturn = () => {
let {editorState} = this.state;
let contentState = editorState.getCurrentContent();
const firstBlock = contentState.getFirstBlock();
const lastBlock = contentState.getLastBlock();
const allSelected = new SelectionState({
anchorKey: firstBlock.getKey(),
anchorOffset: 0,
focusKey: lastBlock.getKey(),
focusOffset: lastBlock.getLength(),
hasFocus: true
});
contentState = Modifier.removeRange(contentState, allSelected, 'backward');
editorState = EditorState.push(editorState, contentState, 'remove-range');
editorState = EditorState.forceSelection(contentState, contentState.getSelectionAfter());
this.setState({editorState});

最新更新