首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >只需在prosemirror中替换节点的内容

只需在prosemirror中替换节点的内容
EN

Stack Overflow用户
提问于 2021-03-22 21:01:19
回答 2查看 1.7K关注 0票数 4

我在一个接收字符串作为输入的函数中:

代码语言:javascript
运行
复制
(text) => {

}

我可以通过Vue道具(props.editor)访问编辑器。我想用这个文本替换当前节点的内容。我似乎找不出该怎么做。我使用的是tiptap2,它是ProseMirror的包装器,可以访问ProseMirror的所有api。

我宁愿不尝试替换整个节点,除非有必要,我也尝试过这样做,我在下面这样做--但也无法让它工作:

代码语言:javascript
运行
复制
(text) => {
        props.editor
          .chain()
          .focus()
          .command(({ tr }) => {
            const node = props.editor.state.schema.nodes.paragraph.create(
              { content: text}
            );
            tr.replaceSelectionWith(node);

            return true;
          })
          .run();
}

非常感谢

EN

回答 2

Stack Overflow用户

发布于 2022-09-10 07:48:18

这个解决方案适用于我在Tiptap版本2中的工作。要做到这一点,一个先决条件是,要替换的文本被标记(突出显示)。

代码语言:javascript
运行
复制
const selection = editor.view.state.selection;
editor.chain().focus().insertContentAt({
    from: selection.from,
    to: selection.to
}, "replacement text").run();
票数 2
EN

Stack Overflow用户

发布于 2022-03-10 19:52:22

我参加聚会迟到了,但这是我在试图为自己找到解决办法时遇到的最高结果。

我的代码是在React的上下文中,因此我得到了一个getPos()支柱,它给出了Prosemirror文档中less节点的位置(我相信这个数字或多或少意味着在React节点之前有多少字符)。这样,我就能够使用这个命令链来替换内容:

代码语言:javascript
运行
复制
import { Node as ProsemirrorNode } from "prosemirror-model";
import { JSONContent, NodeViewProps } from "@tiptap/react";

const NodeViewComponent = (props: NodeViewProps) => 
  // ...

  /**
   * Replace the current node with one containing newContent.
   */
  const setContent = (newContent: JSONContent[]) => {
    const thisPos = props.getPos();

    props.editor
      .chain()
      .setNodeSelection(thisPos)
      .command(({ tr }) => {
        const newNode = ProsemirrorNode.fromJSON(props.editor.schema, {
          type: props.node.type.name,
          attrs: { ...props.attrs },
          content: newContent,
        });

        tr.replaceSelectionWith(newNode);

        return true;
      })
      .run();
  };

  // ...
};

基本上你想:

  1. 将当前选择设置为要替换
  2. 内容的节点,创建和更新一个新节点,即当前节点的副本
  3. ,用新节点替换所选内容。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66753792

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档