我没有解决这个问题,但这可能是我能做的最好的事情,而无需像 @Rishat 提到的那样重新实现历史(如果我弄错了,请告诉我)。
谢谢这个答案 https://stackoverflow.com/a/27028331/192729,我必须理解这个命令:
document.execCommand("insertText", false, text);
这基本上插入text
在当前插入符号位置中当前聚焦的输入中(这就是为什么您不将输入作为参数传递)。当然,这个函数也会相应地更新历史记录。
如果我愿意,我可以协调每个插入(例如**
问题中提到)以这样的方式,一切都会成为历史。但是,这太复杂了,因为每个 markdown 命令都有不同的行为。那就太费力了。
解决方案:
以下代码必须开启componentDidUpdate
,并且应该只被执行以编程方式更改文本后:
// In order to minimize the history problem with inputs, we're doing some tricks:
// - Set focus on the textarea
// - Set the value back to its previous value.
// - Select the whole text (that's the problem)
// - Insert the new value
this.refs.textarea.focus();
this.refs.textarea.value = previousText;
setSelection(this.refs.textarea, 0, previousText.length);
document.execCommand("insertText", false, text);
Effect
Ctrl + Z 工作得很好,但如果您继续返回直到以编程方式更改输入时,它将选择整个文本。我的意思是,历史被保留下来,但代价是如果你回溯得足够多,就会搞乱选择。我相信这已经足够好了,比重新实现输入历史记录更好。
Demo https://andrerpena.github.io/react-mde/.