如何清除 Slate.JS 编辑器中的所有文本

Ste*_*rtz 2 rich-text-editor reactjs slatejs

对于我的一生,我无法弄清楚如何从 slate.js 清除编辑器组件中的所有文本。

我努力了:

Transforms.delete(editor, {}); -> doesn't do anything

editor.deleteBackward("line"); -> only deletes one line, not all
Run Code Online (Sandbox Code Playgroud)

我还尝试手动重新渲染编辑器组件,但遗憾的是没有将其更新到初始状态:(

我一直在翻阅 slate js 文档,但在任何地方都找不到任何东西!如果有人有任何想法,将会非常高兴。

这是编辑器的实现方式:

  const editor = useMemo(() => withHistory(withReact(createEditor())), []);

 <Editable
      key={stateKey}
      onKeyDown={(event: any) => handleKeyDown(event)}
      style={{ overflowWrap: "anywhere", width: "100%" }}
      onPaste={(e) => {
        if (e.clipboardData) {
          if (e.clipboardData.files.length > 0) {
            setFiles([...files, ...Array.from(e.clipboardData.files)]);
            e.preventDefault();
          }
        }
      }}
      decorate={decorate}
      renderLeaf={renderLeaf}
      placeholder="What's happening?"
    />
Run Code Online (Sandbox Code Playgroud)

ran*_*tao 6

您可以改变editor.children并将其设置为“空”值。

const editor = useMemo(() => withHistory(withReact(createEditor())), []);

editor.children = [
    {
        type: "paragraph",
        children: [{ text: "" }]
    }
];
Run Code Online (Sandbox Code Playgroud)

注意:Slate 至少需要一个包含一个空文本节点的数组才能正确渲染。

2023 年 2 月更新:您还需要selection重置.historyeditor

const point = { path: [0, 0], offset: 0 }
editor.selection = { anchor: point, focus: point };
editor.history = { redos: [], undos: [] }; 
editor.children = [{
    type: "paragraph",
    children: [{ text: "" }]
}];
Run Code Online (Sandbox Code Playgroud)